如何使用dplyr在具有过滤function的函数中申请循环?

我想在R中使用dplyr申请循环filter函数。

sumstats<-function(x) { Countries <- c("abc","def","ghi") for (val in Countries) { result <- df %>% filter(COUNTRY.NAME == val) write.xlsx(result, "result.xlsx") } } 

但是这个函数覆盖了excel中现有的表单,我希望将数据写在单独的Excel工作簿上。

轻松完成library(XLConnect)

 ## load the libraries library(XLConnect) library(dplyr) ## constract a dummy data.frame CountryNames <- c('abc','def','ghi') SomeData <- c(21000, 23400, 26800) SomeDate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14')) df <- data.frame(CountryNames, SomeData, SomeDate) # Create Excel File MyExcelFile <- XLConnect::loadWorkbook("Countries_Data.xlsx", create = TRUE) sumstats<-function(x) { Countries <- c("abc","def","ghi") for (val in Countries) { createSheet(MyExcelFile, val) #create a sheet and name it with country name result <- df %>% filter(CountryNames == val) # filter results writeWorksheet(MyExcelFile, result, sheet = val, startRow = 1, startCol = 1) # write results } saveWorkbook(MyExcelFile) # close/write the Excel after finishing the loop } # run the function to check sumstats() 

您必须使用sheetName = val创build图纸名称,并将该图纸追加到您的excel文件中。

 sumstats<-function(x) { Countries <- c("abc","def","ghi") for (val in Countries) { result <- df %>% filter(COUNTRY.NAME == val) write.xlsx(result, file = "result.xlsx", sheetName = val, append = TRUE) } } 

如果你喜欢使用pipe道,你可以像这样连接filterwrite.xlsx

 df %>% filter(COUNTRY.NAME == val) %>% write.xlsx(file = "result.xlsx", sheetName = val, append = TRUE) 

添加了append = TRUE (附加到现有的文件)。