Search code examples
rfor-loopkableextra

R - kableExtra - add_header_above() : Trouble when vectorizing my header into a for loop


I'm trying to vectorize the newheader object into a for loop but it doesn't work :( !

> colnames_data
[1] "4h-7h"     "7h-9h"     "9h-12h"    "12h-15h30" "15h30-18h"
[6] "18h-20h"   "20h-22h"   "22h-4h"   

newheader <- c(" " = 2, setNames(3, colnames_data[1]), setNames(3, colnames_data[2]), setNames(3, colnames_data[3]), setNames(3, colnames_data[4]), setNames(3, colnames_data[5]), setNames(3, colnames_data[6]), setNames(3, colnames_data[7]), setNames(3, colnames_data[8])) 

> newheader
              4h-7h     7h-9h    9h-12h 12h-15h30 15h30-18h 
        2         3         3         3         3         3 
  18h-20h   20h-22h    22h-4h 
        3         3         3 

OK !

for(i in 1:length(colnames_data)){
header_loop[i] <- setNames(3, colnames_data[i])
}

newheader <- c(" " = 2, header_loop)

>newheader 
                  3        <NA>        <NA>        <NA> 
        "2"         "3"     "7h-9h"    "9h-12h" "12h-15h30" 
       <NA>        <NA>        <NA>        <NA> 
"15h30-18h"   "18h-20h"   "20h-22h"    "22h-4h" 

KO ! :( :( :(

Thank you all for your help !


Solution

  • Are you trying to do?

    colnames_data <- c("4h-7h", "7h-9h", "9h-12h", "12h-15h30", "15h30-18h",
                       "18h-20h", "20h-22h","22h-4h")
    
    setNames(c(2, rep(3, length(colnames_data))), c(" ", colnames_data))
    
    #         4h-7h  7h-9h  9h-12h 12h-15h30 15h30-18h  18h-20h  20h-22h  22h-4h 
    #   2         3      3       3         3         3        3        3       3