如何使用dplyr在具有过滤功能的函数中应用循环?

时间:2017-09-18 12:43:46

标签: r excel

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

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工作表上。

2 个答案:

答案 0 :(得分:3)

您必须使用SocketEventHandler.Fire("eventname", payload); 创建工作表名称,并将该工作表附加到excel文件中。

sheetName = val

如果您更喜欢使用管道,可以像这样连接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) } } filter

write.xlsx

添加了df %>% filter(COUNTRY.NAME == val) %>% write.xlsx(file = "result.xlsx", sheetName = val, append = TRUE) (附加到现有文件)。

答案 1 :(得分:2)

轻松完成了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()