我有一个由3个变量组成的数据框架,其中一个称为staff的变量包含13个不同的员工组,变量y称为countries,其中包含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")
}
}