I have table below:
mydf <- data.frame(col0 =c(rep("z",5)),col1= c(rep(0,5)), col2= c(rep(1,5)))
colnames(mydf) <- c("name","aaaa, bbbb", "ccccccc, ddddd-dd")
mynames <- sapply(c(colnames(mydf)), FUN = function(x) gsub("," , ",\\\\", x))
kbl(mydf,
escape=F,
col.names = linebreak(mynames))
I want my column names to break to the next line after ",
" (comma). I tried ",\\\\"
, ",\\"
and ",\n"
. none is working. I m producing an r markdown pdf-output.
any suggestions or hints?
CodePudding user response:
We may use the HTML
tag ("<br>"
) to create the line break for HTML files - gsub/sub
are vectorized, so there is no need to loop over each element of the column names
library(kableExtra)
mynames <- gsub(",", "<br>", names(mydf))
kbl(mydf,
escape=FALSE,
col.names = linebreak(mynames))
If it is a pdf file, the following could work
mynames <- gsub("[,-]", "\n", names(mydf))
-full code - rmarkdown
---
title: "."
output: bookdown::pdf_document2
---
```{r chunk1, echo = FALSE}
library(kableExtra)
mydf <- data.frame(col0 =c(rep("z",5)),col1= c(rep(0,5)), col2= c(rep(1,5)))
colnames(mydf) <- c("name","aaaa, bbbb", "ccccccc, ddddd-dd")
mynames <- gsub(",", "\n", names(mydf))
kbl(mydf,
escape=FALSE,
col.names = linebreak(mynames))
```
-output