Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control knitr kable scientific notation?

Tags:

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?

like image 909
Ben Avatar asked Jun 02 '17 09:06

Ben


2 Answers

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    |
like image 69
DonJ Avatar answered Sep 19 '22 09:09

DonJ


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

like image 38
user2554330 Avatar answered Sep 18 '22 09:09

user2554330