Map + write_csv

Let's say I'm using the gapminder dataset. I'm not, but my problem is very similar. What I want to do is to split file and write multiple csv files (one for each country). But I don't know how to handle the different names. I would like to name each csv file with the name of the country:


I tried the following, but I got multiple errors:

gapminder %>%
  nest(-country) %>%

Good job coming up with a reproducible example on your very first question! :grinning:

I think the nested data.frame set-up works well with the pmap()/pwalk() variants of the map family. These functions are handy for rowwise work, where you want to go through each row of a data.frame and do something with the values in the columns. Here you want to go through each row of the nested data frame and save the data given the country name.

I would use pwalk(), since you don't want anything returned within R but instead are saving something and walk() variants are ...for functions called primarily for their side-effects; it returns .x invisibly.

The code would then look like:

gapminder %>%
    nest(-country) %>%
    pwalk(~write_csv(x = .y, path = paste0(.x, ".csv") ) )

Your data column is the second column (the .y element), so is passed to the first argument in write_csv(). The first column (the .x element) contains the country names, which I paste together with .csv to make the names of the datasets that are saved.


Wow. That is fantastic. I could do it with loops but I'm trying to get into this 'funcional programming' business. But it is not entirely obvious to me. Thanks a million aosmith

1 Like

I saw this was solved, but wanted to give this as a resource, too.

It's a great walk through (pun intended :slight_smile: )


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.