简体   繁体   English

如何将结果导出到R中的excel的不同选项卡中

[英]how to export the results into different tabs of excel in R

I have multiple data frames that I would like to export into different tabs of an excel/csv file. 我有多个数据框,我想导出到excel / csv文件的不同选项卡。 I'll be grouping my 15 data frames into three groups of five. 我将把我的15个数据框分成三组,每组五个。 This way I would have three excel sheets with five different tabs instead of 15 individual excel sheet. 这样我就会有三张带有五个不同标签的excel表,而不是15张单独的excel表。

To export to excel: 要导出到excel:

#fake data 
data_1<-data.frame(c(03,23,4,2))
data_2<-data.frame(c(0223,3,1,2))
data_3<-data.frame(c(0232,3,1,1))
data_4<-data.frame(c(21,23,5,6))
data_5<-data.frame(c(24,5,6,7))

#fake names
mydatasets<-c(data_1,data_2,data_3,data_4,data_5)
mytitles<-c("data1", "data2", "data3","data4", "data5")


#for loop to write out individual csv files
for (i in 1:5)) {
a <- mydatasets[i]
title<-mytitles[i]
myfile <- paste0(title, "_", ".csv")
write.csv(a, file = myfile)
               }

How do I get the above code to merge those csv files into multiple tabs of one csv file or excel file? 如何让上面的代码将这些csv文件合并到一个csv文件或excel文件的多个选项卡中?

CSV files consist of only 1 sheet. CSV文件仅包含1张。 An alternative would be to write to XLSX. 另一种方法是写入XLSX。 The function xlsx::write.xlsx takes an argument sheetName : 函数xlsx::write.xlsx接受参数sheetName

library(xlsx)

# Use data from the question
for (i in seq_along(mydatasets)) {
  write.xlsx(x = mydatasets[i], 
             file = "myfile.xlsx", 
             sheetName = mytitles[i],
             append = TRUE)
}

Note append = TRUE to avoid overwriting the file instead of appending sheets to it. 注意append = TRUE以避免覆盖文件而不是向其附加工作表。

The xlsx package depends on rJava . xlsx包依赖于rJava Using that package for the first time causes trouble sometimes – see this question for a common solution. 首次使用该软件包会导致问题 - 请参阅此问题以获得常见解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM