How to control knitr kable scientific notation?

自闭症网瘾萝莉.ら 提交于 2019-12-05 01:31:45

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:

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