代码之家  ›  专栏  ›  技术社区  ›  user3018495

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

  •  1
  • user3018495  · 技术社区  · 7 年前

    我有一个由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")
    
    }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   count    7 年前

    考虑以下最小示例:

    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