rdplyrtidyversetidyrreadr

How can I write a nested tibble to separate files


I want to write separate .csv files for each group in a nested tibble. So far I tried something like

mtcars %>% 
dplyr::group_by(cyl) %>% tidyr::nest() %>%
dplyr::group_walk(~ readr::write_csv(.x$data, paste0(.y$cyl, ".csv")))

This gives the error message

Error in write_delim(x, file, delim = ",", na = na, append = append, col_names = col_names, : is.data.frame(x) is not TRUE

I based my code on this answer https://stackoverflow.com/a/54807068/2069472

I can unnest my data and use @akrun's method. How do I do it directly from a nested tibble?


Solution

  • You could use write.csv instead like this:

    library(dplyr)
    library(tidyr)
    mtcars %>% 
      dplyr::group_by(cyl) %>% 
      tidyr::nest() %>%
      dplyr::group_walk(~ write.csv(.x$data, paste0(.y$cyl, ".csv")))
    
    df_example = read.csv("4.csv")
    head(df_example)
    #>   X  mpg  disp hp drat    wt  qsec vs am gear carb
    #> 1 1 22.8 108.0 93 3.85 2.320 18.61  1  1    4    1
    #> 2 2 24.4 146.7 62 3.69 3.190 20.00  1  0    4    2
    #> 3 3 22.8 140.8 95 3.92 3.150 22.90  1  0    4    2
    #> 4 4 32.4  78.7 66 4.08 2.200 19.47  1  1    4    1
    #> 5 5 30.4  75.7 52 4.93 1.615 18.52  1  1    4    2
    #> 6 6 33.9  71.1 65 4.22 1.835 19.90  1  1    4    1
    

    Created on 2023-03-01 with reprex v2.0.2


    If you want to use write_csv, you have to make sure your input is a dataframe using as.data.frame like this:

    library(readr)
    library(dplyr)
    library(tidyr)
    mtcars %>% 
      dplyr::group_by(cyl) %>% 
      tidyr::nest() %>%
      dplyr::group_walk(~ write_csv(as.data.frame(.x$data), paste0(.y$cyl, ".csv")))
    
    df_example = read.csv("4.csv")
    head(df_example)
    #>    mpg  disp hp drat    wt  qsec vs am gear carb
    #> 1 22.8 108.0 93 3.85 2.320 18.61  1  1    4    1
    #> 2 24.4 146.7 62 3.69 3.190 20.00  1  0    4    2
    #> 3 22.8 140.8 95 3.92 3.150 22.90  1  0    4    2
    #> 4 32.4  78.7 66 4.08 2.200 19.47  1  1    4    1
    #> 5 30.4  75.7 52 4.93 1.615 18.52  1  1    4    2
    #> 6 33.9  71.1 65 4.22 1.835 19.90  1  1    4    1
    

    Created on 2023-03-01 with reprex v2.0.2