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



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

下面是我到目前为止的代码,我没有收到任何错误,但我也没有得到任何输出。

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

最新更新