rlatexxtable

Standard Deviation in parenthesis: Latex R


I want standard deviation in the parenthesis for a data frame. Since I'm using Latex, I want the output in something like: meanValue (sdValue).

The data frame that I have contains columns for mean and sd values for each variable that I'm interested in.

For example, how would you put standard deviation in parenthesis?

iris %>% group_by(Species) %>% summarize(MeanPetal = mean(Petal.Length), sdPetal = sd(Petal.Length))

Solution

  • Use some formatting function when you calculate sdPetal. For example,

    
    library(tidyverse)
    iris %>% group_by(Species) %>% summarize(MeanPetal = mean(Petal.Length), 
                                             sdPetal = sprintf("(%.2f)", sd(Petal.Length)))
    #> `summarise()` ungrouping output (override with `.groups` argument)
    #> # A tibble: 3 x 3
    #>   Species    MeanPetal sdPetal
    #>   <fct>          <dbl> <chr>  
    #> 1 setosa          1.46 (0.17) 
    #> 2 versicolor      4.26 (0.47) 
    #> 3 virginica       5.55 (0.55)
    

    Created on 2020-11-28 by the reprex package (v0.3.0)

    If you want this in LaTeX, just pass it through knitr::kable:

    
    library(tidyverse)
    library(knitr)
    iris %>% 
        group_by(Species) %>% 
        summarize(MeanPetal = mean(Petal.Length), 
                  sdPetal = sprintf("(%.2f)", sd(Petal.Length)),
                  .groups = "keep") %>%
        kable(format = "latex") %>% cat
    #> 
    #> \begin{tabular}{l|r|l}
    #> \hline
    #> Species & MeanPetal & sdPetal\\
    #> \hline
    #> setosa & 1.462 & (0.17)\\
    #> \hline
    #> versicolor & 4.260 & (0.47)\\
    #> \hline
    #> virginica & 5.552 & (0.55)\\
    #> \hline
    #> \end{tabular}
    

    Created on 2020-11-28 by the reprex package (v0.3.0)

    (You may or may not need the cat at the end, depending on how you are using this code. I needed it because I was producing Markdown code using reprex::reprex.)