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

时间:2018-02-16 16:50:47

标签: r excel loops worksheet

我正在尝试获取我拥有的excel文件(假设它有4列名为“one”,“two”,“three”,“four”,excel文件称为“test”)并单独创建每列的工作表。 因此,在我的“测试”文件中,我将有4个工作表。在第一个工作表中将是“one”列中的所有值,下一个工作表将是“two”列中的所有值,等等。

我尝试使用这样的循环:

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

但它不起作用。

任何帮助表示赞赏!!!

1 个答案:

答案 0 :(得分:0)

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

colnames(mtcars[,1])
NULL

首先,我将展示用于制作我认为您想要的内容的openxlsx代码。然后,根据您在xlsx看到的损坏错误,我会使用openxlsx包显示代码。我希望这些评论足以表达代码的作用。

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")