Search code examples
rformattingr-markdown

Rmarkdown: Merge rows in a single column with without disturbing the rest of the table and export to excel


I have been trying to figure this out all morning. I want to collapse rows in a single column without summing the rest of the table. I don't know the proper terminology for what I am trying to do. I need to export the result to Excel, so I don't think I can use kableExtra to solve this as I normally would. Any suggestion will be helpful. The first table is what I have in R. The second table is the desired product.

The data and my R-code is here https://drive.google.com/drive/folders/156RqWANAu2wL-Tr-x_wsdZ_qjEgM_5jM?usp=sharing

What I have

What I Want


Solution

  • library(dplyr)
    library(openxlsx)
    # I assume that your data is in a data frame called 'df'
    result <- df %>%
      group_by(DEPT, Degree) %>%
      summarise(across(everything(), sum, na.rm = TRUE))
    # Now you can write the result to an Excel file
    write.xlsx(result, "output.xlsx")
    

    You can use it with customized parameters in across() function. This is brief letters and if you give me more information, I'd happy to help you!