为 R 中一个 excel 文件中的每一列创建新工作表

Create new worksheet for each column within one excel file in R

我正在尝试获取我拥有的 excel 文件(假设它有 4 列名为 "one"、"two"、"three"、"four" excel 文件名为 "test") 并为每一列制作一个单独的工作表。 所以在我的 "test" 文件中,我会有 4 个工作表。在第一个工作表中将是 "one" 列中的所有值,下一个工作表将是 "two" 列中的所有值,依此类推

我试过使用这样的循环:

for(i in 1:ncol(test)){
write.xlsx(test[i,,], file="filename.xlsx", sheetName=names(test)[i])
}

但是没有用。

感谢任何帮助!!!

一个问题是括号内的数据框引用中有两个逗号,第一个括号内的参数将抓取行而不是列。此外,与数据框不同,向量没有列名:

colnames(mtcars[,1])
NULL

首先,我将展示 openxlsx 我用来生成我认为您想要的内容的代码。考虑到您在 openxlsx 中看到的损坏错误,然后我使用 xlsx 包显示代码。我希望评论能充分表达代码的作用。

openxlsx 包版本

library(openxlsx)
# Create the workbook data structure as wb
wb <- createWorkbook()
for(i in 1:ncol(mtcars)){
# shtname will be the ith column name in mtcars  
  shtname = names(mtcars)[i]
# add a sheet to wb that is named the ith column name
  addWorksheet(wb, shtname)
# Turn the ith column vector of mtcars into a dataframe 
# so we can give the object a column name
  mtcars_col_frm <-  data.frame(mtcars[,i])
  colnames(mtcars_col_frm) <- shtname
# write into that sheet the ith column of mtcars
  writeData(wb, i, mtcars_col_frm, colNames = TRUE)
}
# save all of the created sheets into a workbook
# Note that I used overwrite = TRUE to avoid 
# "File already exists" error you may experience
saveWorkbook(wb, file="filename.xlsx", overwrite = TRUE)

xlsx 包版本

library(xlsx)
# Create the workbook data structure as wb
wb <- xlsx::createWorkbook()
for(i in 1:ncol(mtcars)){
  # shtname will be the ith column name in mtcars  
  shtname = names(mtcars)[i]
  # add a sheet to wb that is named the ith column name
  sht <- xlsx::createSheet(wb, shtname)
  # Turn the ith column vector of mtcars into a dataframe 
  # so we can give the object a column name
  mtcars_col_frm <-  data.frame(mtcars[,i])
  colnames(mtcars_col_frm) <- shtname
  # write into that sheet the ith column of mtcars
  xlsx::addDataFrame(x = mtcars_col_frm, sheet = sht, row.names = FALSE)
}
# save all of the created sheets into a workbook
xlsx::saveWorkbook(wb, file="filename.xlsx")