Quantcast
Channel: Active questions tagged kable - Stack Overflow
Viewing all articles
Browse latest Browse all 105

How to merge column names with data frame (or kable) in R?

$
0
0

Newbie in R here.In Excel, if you click and drag to select multiple cells, you can click on "merge cells" to convert multiple cells into one. Similar mindset, I want to do this in R.

Take this dataframe for this example:

library(kableExtra)library(magrittr)library(knitr)We_Love_Colours <- data.frame(  Name = c("Colours", "", ""),  G = c("green","green","green"),  B = c("blue", "blue", "blue"),  R = c("red", "red", "red"),  Y = c("yellow", "yellow", "yellow"),  P = c("purple", "purple", "purple"),  C = c("cyan", "cyan", "cyan")) kable(We_Love_Colours, format = "html", escape = FALSE, row.names = FALSE, caption = "Table 1.0: Rainbow?") %>%  kable_styling(    bootstrap_options = c("striped"),    full_width = FALSE,    position = "center"  )

And the output should look something like the image I'm uploading here.https://imgur.com/a/QyRciV3

I would like to merge the column names "G", "B", "R", "Y", "P", "C" into a single cell and write "Colours". How can I do this?

Just like with everything, I tried to get help from ChatGPT and it suggested to add this part:

kable(We_Love_Colours, format = "html", escape = FALSE, row.names = FALSE, caption = "Table 1.0: Rainbow?") %>%  add_header_above(c(" " = 1, "Colours" = 6)) %>%  kable_styling(    bootstrap_options = c("striped"),    full_width = FALSE,    position = "center"

However, that just generated a new row above the column names and "Colours" hovered over the column names. I was seeking to replace those column names with a single column name.


Viewing all articles
Browse latest Browse all 105

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>