How to control knitr kable scientific notation?

2020-08-09 08:58发布

I have a data frame like this:

> summary
  variable         value
1     var1  5.810390e-06
2     var2  5.018182e-06
3     var3  5.414286e-06
4     var4  3.000779e+02
5     var5 -2.105123e+01
6     var6  8.224229e-01

I want to print it in a word document using knitr/kable. Thus I used the following function:

knitr::kable(summary,
             row.names = FALSE,
             col.names = c("Variable", "Mean"))

But the result is not satisfying:

enter image description here

I'm OK with variables 4 to 6, but variables 1 to 3 are really not easy to read this way... Is there a way to control this format?

标签: r knitr
2条回答
欢心
2楼-- · 2020-08-09 09:12

The most general way is to do the formatting yourself, and send a dataframe of character variables to kable. For example, this doesn't give the nicest display, but it shows how to handle the first 3 rows separately:

df <- data.frame(variable = paste0("var", 1:6),
         value =c(5.810390e-06, 5.018182e-06, 5.414286e-06, 3.000779e+02, -2.105123e+01, 8.224229e-01))
formatted <- df
formatted$value[1:3] <- format(df$value[1:3], digits = 3)
formatted$value[4:6] <- format(df$value[4:6], digits = 3)
knitr::kable(formatted)

This produces the following output:

enter image description here

查看更多
劫难
3楼-- · 2020-08-09 09:26

You can also use as.character() and signif():

# using the data frame from the previous answer:

df <- data.frame(variable = paste0("var", 1:6),
     value =c(5.810390e-06, 5.018182e-06, 5.414286e-06, 3.000779e+02, 
              -2.105123e+01, 8.224229e-01))

df %>% dplyr::mutate_if(is.numeric, funs(as.character(signif(., 3)))) %>%
    kable(.)

Which gives:

|variable |value    |
|:--------|:--------|
|var1     |5.81e-06 |
|var2     |5.02e-06 |
|var3     |5.41e-06 |
|var4     |300      |
|var5     |-21.1    |
|var6     |0.822    |
查看更多
登录 后发表回答