Search code examples
rkable

Format input in kable table R


This is my reproduceable code:

library(splines)
var = c(1,2,3,4,5,6,7,8,9,10)
degree.freedom <- c(4,5,6)

list1 <- list()
list2 <- list()
for (i in 1:length(degree.freedom)){
  attr <- attr(bs(var, df=degree.freedom[i]) ,"knots")
  list1[[i]] <- names(attr)
  list2[[i]] <- unname(attr)
}
knitr::kable(cbind(list1,list2), col.names=c("list1","list2"))

WHere I obtain the following table:

enter image description here

But I would like to obtain a more pretty table as:

enter image description here

what can I do to list1 and list2 to obtain the desired table?

NB: I made the desired table using:

list1 <- c("[50%]","[33.33%, 66.67%]","[25%, 50%, 75%]")
list2 <- c("[5.0]","[4.0, 7.0]","[3.25, 5.50, 7.75]")

Solution

  • If you have a list, such as list1:

    [[1]]
    [1] "50%"
    
    [[2]]
    [1] "33.33333333333332859638%" "66.66666666666665719276%"
    
    [[3]]
    [1] "25%" "50%" "75%"
    

    You can convert to comma-separated values, enclosed in brackets by:

    paste0('[', lapply(list1, paste, collapse = ', '), ']')
    
    [1] "[50%]"                                                "[33.33333333333332859638%, 66.66666666666665719276%]"
    [3] "[25%, 50%, 75%]"
    

    In this case, lapply will use paste together each element, and collapse will insert commas between values.

    Since you are using bs from splines, it generates percentages which are character values. The number of digits is dependent on your settings. For me:

    getOption("digits")
    [1] 22
    

    (Note that the random digits towards the end are noise...)

    You can specify the number of digits printed (not decimal places) by setting:

    options(digits = 4)
    

    Which would give you:

    |list1            |list2             |
    |:----------------|:-----------------|
    |[50%]            |[5.5]             |
    |[33.33%, 66.67%] |[4, 7]            |
    |[25%, 50%, 75%]  |[3.25, 5.5, 7.75] |
    

    Also note: kable allows for digits to be set; however, this applies to numeric values. The character values would not be affected.