使用R在具有动态sheetNames的excel中编写多个工作表 [英] Use R to write multiple sheets in excel with dynamic sheetNames
问题描述
这可以使用 for
循环轻松完成,但是我正在寻找使用 lapply
或 dplyr
的解决方案.
This can easily be done using for
loop but I am looking for a solution with lapply
or dplyr
.
我有多个数据框,希望将它们导出到单独的工作表中的excel文件中(我在相似的行上看到了很多问题和答案,但是找不到动态解决命名表的问题).
I have multiple dataframes which I want to export to excel file in separate sheets (I saw many questions and answers on similar lines but couldn't find one that addressed naming sheets dynamically).
我想通过数据框的名称来命名工作表.为简单起见,我将数据帧命名为一种模式(例如df1至df10).我该怎么做?
I want to name the sheet by the name of the dataframe. For simplicity, I have named the dataframes in a pattern (say df1 to df10). How do I do this?
下面是一个可重现的示例,我尝试使用两个数据框 mtcars
和 cars
(正在运行,但没有好的工作表名称).
Below is a reproducable example with my attempt with two dataframes mtcars
and cars
(which is working, but without good sheetnames).
names_of_dfs=c('mtcars','cars')
# variable 'combined' below will have all dfs separately stored in it
combined = lapply(as.list(names_of_dfs), get)
names(combined)=names_of_dfs # naming the list but unable to use below
multi.export=function(df,filename){
return(xlsx::write.xlsx(df,file = filename,
sheetName = paste0('sheet',sample(c(1:200),1)),
append = T))
}
lapply(combined, function(x) multi.export(x,filename='combined.xlsx'))
如果可以使用其他r包更轻松地完成此操作,请提出建议.
In case it can be done more easily with some other r package then please do suggest.
推荐答案
尝试如下操作:
library(xlsx)
#Workbook
wb = createWorkbook()
#Lapply
lapply(names(combined), function(s) {
sht = createSheet(wb, s)
addDataFrame(combined[[s]], sht)
})
saveWorkbook(wb, "combined.xlsx")
这篇关于使用R在具有动态sheetNames的excel中编写多个工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!