0

I have already written a function that helps create a csv.file for each state.

specify.state <- function(type.state) {
  new.state <- any.drinking %>% 
    filter(state == type.state)
    write.csv(new.state,paste("any_drinking_", type.state, ".csv"), row.names = FALSE)
}

Since there are 51 states in my data frame, I'm wondering how to run this function for each state at the same time by using dplyr. So I can get 51 different files at the same time.

Thank you very much for helping!

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • Any particular reason why you want to filter for each type.state value? You can split the original data frame by state to create a list of subsetted data frame, then save them using one of the solutions to [this question](https://stackoverflow.com/questions/4209512/write-list-of-data-frames-to-separate-csv-files-with-lapply). – Z.Lin Oct 23 '17 at 05:46

1 Answers1

0

The tidy method would be something like this:

library(purrr)
library(dplyr)

walk(any.drinking$state, 
    function(x) write.csv(x, paste0("any_drinking_", x, ".csv"), row.names=FALSE))
David Klotz
  • 2,401
  • 1
  • 7
  • 16
  • Thank you! however, we are only allowed to use dplyr. I edit some part of your code and it comes like `new.multi.grouped.any.drinking <- split(any.drinking, any.drinking$state) lapply(names(new.multi.grouped.any.drinking),specify.state)`. May I ask is there a way to combine those two lines in just one? I really appreciate your help! Thank you1 – Yiran Jia Oct 26 '17 at 04:17
  • You can use `group_by` followed by `do`. You'll need to modify your function so it returns a data frame: `drink_write <- function(x){ write.csv(x, paste0("any_drinking_", unique(x$state), ".csv"), row.names=FALSE) return(x) }`, then `any.drinking %>% group_by(state) %>% do(drink_write(.))`. See also https://stackoverflow.com/a/41233405 and https://stackoverflow.com/questions/23898294 – David Klotz Oct 26 '17 at 18:58