R - knitr:kable - removing individual headers and adding single header on multiple columns

谁说我不能喝 提交于 2019-12-24 08:02:05

问题


R code in Rmarkdown file:

col1 <- c("dummydata","dummydata","dummydata")
col2 <- c("dummydata","dummydata","dummydata")  
col3 <- c("dummydata","dummydata","dummydata")
col4 <- c("dummydata","dummydata","dummydata")
col5 <- c("dummydata","dummydata","dummydata")
col6 <- c("dummydata","dummydata","dummydata")
col7 <- c("dummydata","dummydata","dummydata")
col8 <- c("dummydata","dummydata","dummydata")

df1 <- data.frame(col1,col2,col3,col4,col5,col6,col7,col8)

kable(df1, format="html",table.attr='class="myTable"') %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
add_header_above(c("Group1" = 2, "Group2" = 2,"Group3" = 2, "Group4" = 2))

Output:

ISSUE: I only want headers on combined columns i.e. Group1, Group2 etc. And I want to remove headers on individual columns i.e. col1, col2 etc.

Is there any way to do this using dataframe, html/javascript, Rmarkdown or any R package?


回答1:


You should get comfortable with regular expressions and the gsub-function if you come accros such problems more often.

here is a solution, the first row is your last line of code enhanced by "x <-"

x <- kable(df1, format="html",table.attr='class="myTable"') %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
add_header_above(c("Group1" = 2, "Group2" = 2,"Group3" = 2, "Group4" = 2))

gsub("</th></tr><tr>.*</thead>","</thead>",x)

gsub works as follows: look for a match to the first parameter, replace it with the second and do all that to the variable provdided as third parameter. The dot star (.*) within the first parameter says that any type and number of characters can follow before the closing follows in the third parameter. The algorithm is greedy that is it tries to find the longest matching string. Since there is only one in this input parameter, this works fine here.



来源:https://stackoverflow.com/questions/44748726/r-knitrkable-removing-individual-headers-and-adding-single-header-on-multip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!