Allow duplicated names in binded tables

Viewed 267

UPDATE for why I changed my votes.

This code has the table displayed but R doesn't knit pdf.

all_jt %>%
kbl(longtable = T, booktabs = T, 
      caption = "table") %>% 
  remove_column(7) %>%
  add_header_above(c(" " = 2, "Year 1" = 4, "Year 2" = 4)) %>% 
  kable_styling(latex_options = c("repeat_header")) 

Quitting from lines 13-37 (test_table.Rmd) 
Error in remove_column(., 7) : 
  Removing columns was not implemented for latex kables yet

switching to select(-7) as in here Remove_Column from a kable table which will be output as latex/pdf doesn't work because R doesn't like duplicated column names.

I have two ANOVA tables, jt_1 and jt_2 below, that I want to merge and keep 1 column for the model term only. As I remove the duplicated column, R added .1 to the tail of columns' 7, 8, 9 and 10 names.

library(emmeans)
library(stringr)

warp.lm <- lm(breaks ~ wool * tension, data = warpbreaks)

jt_1 <- print(joint_tests(warp.lm), export = T) %>% as.data.frame() 


jt_2 <- jt_1

all_jt <- cbind(jt_1, jt_2) %>% 
  setNames(gsub("summary.", "", colnames(.))) 

all_jt[,-6]%>% #to remove the duplicated column for model term
 data.frame(check.names = F) %>% 
kbl(longtable = T, booktabs = T, 
    caption = "table") %>% 
  add_header_above(c(" " = 2, "Year 1" = 4, "Year 2" = 4)) %>% 
  kable_styling(latex_options = c("repeat_header")) 

Here is a brief idea of what I need.

enter image description here Many thanks in advance.

2 Answers

You can use remove_column function from kableExtra to remove a column instead of all_jt[,-6] which makes the column name unique.

library(knitr)
library(kableExtra)

all_jt %>%
kbl(longtable = T, booktabs = T, 
      caption = "table") %>% 
  remove_column(7) %>%
  add_header_above(c(" " = 2, "Year 1" = 4, "Year 2" = 4)) %>% 
  kable_styling(latex_options = c("repeat_header")) 

enter image description here

R does not like duplicate column names in data.frames. If you step through your last code block line by line you will notice that all_jt[, -6] makes column names unique by adding the ".1" suffix.

The/a solution is to provide column names to kbl directly, e.g.

all_jt[,-6] %>%
    kbl(longtable = T, booktabs = T, 
        col.names = gsub("\\.\\d", "", names(.)),
        caption = "table") %>% 
    add_header_above(c(" " = 2, "Year 1" = 4, "Year 2" = 4)) %>% 
    kable_styling(latex_options = c("repeat_header")) 

This produces

enter image description here

Related