Search code examples
rrstudiokablekableextra

R/Rstudio: Is there a way from "kableExtra" tables to add the additional headers using R values?


I have created a kable object using function %>% adding additional headers with the appropiate function. My problem is when I try to add these additional headers using values from objects in R.

(t is a df with 9 columns. In order to test this I add a code to create a sample df to use t)

t<-data.frame(k=seq(1:2))
t<-cbind(t,rep(t,7))
t %>% kbl(caption = paste("Results Data")) %>%
kable_classic(full_width = F,font_size = 11) %>% 
add_header_above(c(" " = 1," " = 1,"30±2ºC" = ncol(t)-2)) %>% 
add_header_above(c(" " = 1,"Time (Months)" = ncol(t)-1))

When you try to add headers from a R object values the system does not work:

t<-data.frame(k=seq(1:2))
t<-cbind(t,rep(t,7))
temp <- "30±2ºC"
t %>% kbl(caption = paste("Results Data")) %>%
kable_classic(full_width = F,font_size = 11) %>% 
add_header_above(c(" " = 1," " = 1,temp = ncol(t)-2)) %>% 
add_header_above(c(" " = 1,"Time (Months)" = ncol(t)-1))

The additional header is fixed as "temp" instead of the actual value.

t<-data.frame(k=seq(1:2))
t<-cbind(t,rep(t,7))
temp <- "30±2ºC"
t %>% kbl(caption = paste("Results Data")) %>%
kable_classic(full_width = F,font_size = 11) %>% 
add_header_above(c(" " = 1," " = 1,paste(temp) = ncol(t)-2)) %>%
add_header_above(c(" " = 1,"Time (Months)" = ncol(t)-1))

Output:

Error: unexpected '=' in:
"    kable_classic(full_width = F,font_size = 11) %>% 
    add_header_above(c(" " = 1," " = 1,paste(temp) ="

I would like to know it anybody has been able to use values from R in kable additional headers.

Thank you!


Solution

  • I believe this will give you what you want. The key is to construct the vector that defines the header in advance, not on the fly.

    library(knitr)
    library(kableExtra)
    
    t<-data.frame(k=seq(1:2))
    t<-cbind(t,rep(t,7))
    
    temp <- "30±2ºC"
    firstHeader <- c(2, ncol(t)-2)
    names(firstHeader) <- c(" ", temp)
    t %>% kbl(caption = paste("Results Data")) %>%
    kable_classic(full_width = F,font_size = 11) %>%
    add_header_above(firstHeader) %>%
    add_header_above(c(" " = 1,"Time (Months)" = ncol(t)-1))
    

    Which gives enter image description here