How to control knitr kable scientific notation?

送分小仙女□ 提交于 2019-12-10 01:54:46

问题


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:

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?


回答1:


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:




回答2:


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    |


来源:https://stackoverflow.com/questions/44325464/how-to-control-knitr-kable-scientific-notation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!