R 循环 - 子集文件和 运行 xlsx 代码

R loop - Subset the file and run xlsx code

我有一个由 3 个变量组成的数据框,其中一个称为员工的变量包含 13 个不同的员工组,变量 y 称为国家/地区,其中包含员工所在的 10 个国家/地区。每个国家/地区都应放入自己的excel 具有相应员工组的工作簿。所以我应该有 13 x 10 排列,我想要每个国家/地区的 excel 工作簿,我正在使用 XLSX 包来这样做,但我想创建一个循环来按国家/地区过滤数据并将每个国家/地区保存到它自己的excel 文件,这样我就不必将代码复制 10 次了。我的数据框名称是 "Cost"

下面是我目前的代码,没有错误,但也没有输出。

countries <- c("Ireland", "Scotland", "England", "Wales", "Germany", "Italy", "Russia", "Denmark", "USA", "Spain")

for(countriesb in countries){

#create excel output for each country
wb = createWorkbook(type="xlsx")

Costsheet = createSheet(wb, "Country")

Cost%>% filter(country==countriesb)

xlsx.addTitle<-function(sheet, rowIndex, title, titleStyle){
rows <-createRow(sheet,rowIndex=rowIndex)
sheetTitle <-createCell(rows, colIndex=1)
setCellValue(sheetTitle[[1,1]], title)
setCellStyle(sheetTitle[[1,1]], titleStyle)

TITLE_STYLE <- CellStyle(wb)+ Font(wb,  heightInPoints=16, 
                                   color="blue", isBold=TRUE, underline=0)

xlsx.addTitle(Cost, rowIndex=1, title="Cost",titleStyle = TITLE_STYLE)
addDataFrame(Cost, Costsheet, startRow =3, row.names=FALSE)

saveWorkbook(wb, "country.xlsx")

}
}

考虑以下最小示例:

require("xlsx")

wb = createWorkbook(type="xlsx") #Create a workbook outside of the loop

x <- c("USA","UK","NL")

for(i in x){
    sh = createSheet(wb, as.character(i)) #Create Sheets inside the loop with corresponding x-values as sheet names
    addDataFrame(mtcars,sh, startRow =3, row.names=FALSE) # Add your data to the sheets
}

saveWorkbook(wb, "C:/YourPath/Yourfile.xlsx") # save your workbook outside the loop