如何将标题添加到多个列

时间:2021-01-18 19:57:40

标签: r

我有一个如下所示的 data.frame:

enter image description here

可以使用代码构建示例数据:

df<- structure(list(Name = c("B2", "A2", "B3", "A3", "B4", "A4"), 
    Var1.x = c(29, 56, 25, 11, 0, 58), Var2.x = c(65, 35, 
    15, 11, 0, 58), Var3.x = c(95, 632, 25, 11, 0, 58), Var1.y = c(29, 
    56, 25, 11, 0, 58), Var2.y = c(29, 56, 25, 11, 0, 58), Var3.y = c(29, 
    56, 25, 11, 0, 58)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

我需要把它写成一个excel文件。如何在输出中添加标题?这是我可以修改 df 以实现此目标的方法吗?如果我们需要您的合并单元格来构建标题,是否可以找到具有 .x 的列并合并到 Subject x 而不是计算列号?

理想的输出是这样的: enter image description here

目前我有我的代码:

wb <- createWorkbook()
addWorksheet(wb, sheetName = "Question")
writeData(wb, sheet = "Question", x = df, colNames = TRUE, startCol = 1, startRow = 2)
saveWorkbook(wb, paste("C:/Question.xlsx"),overwrite = TRUE)

1 个答案:

答案 0 :(得分:2)

这是使用 xlsx 包的方法:

library(xlsx)
library(stringr) # For str_extract. regmatches is very cumbersome 
workbook <- createWorkbook()
sheet <- createSheet(workbook, sheetName = "Question")
row <- createRow(sheet, 1)
cells <- createCell(row, seq_along(colnames(df)))

suffixes <- unique(na.omit(str_extract(colnames(df),"(?<=\\.)\\w$")))
for(suf in suffixes){
  ind <- grep(paste0("\\.",suf,"$"),colnames(df))
  setCellValue(cells[[ind[1]]], paste0("Subject ",toupper(suf)))
  setCellStyle(cells[[ind[1]]], CellStyle(workbook) + Alignment(horizontal = "ALIGN_CENTER"))
  addMergedRegion(sheet, startRow = 1, endRow = 1,
                  startColumn = ind[1],
                  endColumn = tail(ind,1))
}

addDataFrame(as.data.frame(df), sheet, row.names=FALSE, startRow=2)
saveWorkbook(workbook,'df.xlsx')

enter image description here