How to apply for loop inside a function which has filter function using dplyr?

Viewed 434

I would like to apply for loop on a filter function using dplyr in R.

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

However this function overwrites the existing sheet on excel, I would like the data to be written on separate excel sheets on a single workbook.

2 Answers
Related