R (xlsx) - 根据列值从 DF 写入多个 Excel 文件
R (xlsx) - Write Multiple Excel Files From DF Based on Column Values
我有一个包含很多行(>300,000)的数据框,我想使用 xlsx 包将其写入多个 Excel 文件。
样本数据-
myData <- data.frame(Letter=c("A","B","C","D","E","F","G","H","I","J"),
Fruit = c("Apples", "Pears", "Oranges",
"Carrots", "Mangoes", "Potatoes",
"Bananas", "Plums","Grapes",
"Broccoli"),
Country = c("Scotland", "Scotland", "Scotland",
"England", "England", "England",
"Wales", "Wales", "Wales",
"Ireland"))
因此,根据示例数据,我想按 'Country' 列拆分我的 Excel 工作簿。将有 4 个 Excel 文件以国家/地区名称作为文件名,我希望它们如下所示 -
Letter Fruit Country
------------------------
A Apples Scotland
B Pears Scotland
C Oranges Scotland
从数据集中取出 'Country' 列将是一个奖励。
我已经想出如何使用 For 循环将它们拆分成多个数据帧,然后我可以为每个国家/地区写一条 'write.xlsx' 行。但我的国家名单是动态的。请参见下面的示例 -
for (i in unique(myData$Country)) {
test <- paste0("excel", i)
assign(test, myData[myData$Country == i,])
}
我一直在努力将 write.xlsx 函数放入该循环,但也许有更好的方法。
有人可以帮忙吗?
我只是将它们拆分成一个列表,然后使用 lapply
作为 write.xlsx。我建议 lapply
而不是 for-loop
。
myDatalist <- split(myData, myData$Country)
lapply(1:length(myDatalist), function(x) write.xlsx(myDatalist[[x]],
file = paste0(names(myDatalist[x]), ".xlsx"), row.names = FALSE))
这只是将函数应用于列表。
使用 For 循环方法...
List <- list()
for (i in unique(myData$Country)) {
test <- paste0("excel", i)
testlist<-list(assign(test, myData[myData$Country == i,]))
List[[test]]<-testlist
}
正如@Anonymous coward 所示,只需将该函数应用于列表
lapply(1:length(List), function(x) write.xlsx(List[[x]],
file = paste0(names(List[x]), ".xlsx"), row.names = FALSE))
我有一个包含很多行(>300,000)的数据框,我想使用 xlsx 包将其写入多个 Excel 文件。
样本数据-
myData <- data.frame(Letter=c("A","B","C","D","E","F","G","H","I","J"),
Fruit = c("Apples", "Pears", "Oranges",
"Carrots", "Mangoes", "Potatoes",
"Bananas", "Plums","Grapes",
"Broccoli"),
Country = c("Scotland", "Scotland", "Scotland",
"England", "England", "England",
"Wales", "Wales", "Wales",
"Ireland"))
因此,根据示例数据,我想按 'Country' 列拆分我的 Excel 工作簿。将有 4 个 Excel 文件以国家/地区名称作为文件名,我希望它们如下所示 -
Letter Fruit Country
------------------------
A Apples Scotland
B Pears Scotland
C Oranges Scotland
从数据集中取出 'Country' 列将是一个奖励。
我已经想出如何使用 For 循环将它们拆分成多个数据帧,然后我可以为每个国家/地区写一条 'write.xlsx' 行。但我的国家名单是动态的。请参见下面的示例 -
for (i in unique(myData$Country)) {
test <- paste0("excel", i)
assign(test, myData[myData$Country == i,])
}
我一直在努力将 write.xlsx 函数放入该循环,但也许有更好的方法。
有人可以帮忙吗?
我只是将它们拆分成一个列表,然后使用 lapply
作为 write.xlsx。我建议 lapply
而不是 for-loop
。
myDatalist <- split(myData, myData$Country)
lapply(1:length(myDatalist), function(x) write.xlsx(myDatalist[[x]],
file = paste0(names(myDatalist[x]), ".xlsx"), row.names = FALSE))
这只是将函数应用于列表。
使用 For 循环方法...
List <- list()
for (i in unique(myData$Country)) {
test <- paste0("excel", i)
testlist<-list(assign(test, myData[myData$Country == i,]))
List[[test]]<-testlist
}
正如@Anonymous coward 所示,只需将该函数应用于列表
lapply(1:length(List), function(x) write.xlsx(List[[x]],
file = paste0(names(List[x]), ".xlsx"), row.names = FALSE))