简体   繁体   中英

How to write to disk data from each element of nested data frame in R?

My question is directly related to this one: In R, write each nested data frame to a CSV , but I am not able to get the solution to work and would like to avoid needing to install the extra required package purrrlyr .

I need to write each element (data.frame) of a nested data.frame to a table, with the name of each element corresponding to the first column of the nested data.frame:

ir <- iris %>% group_by(Species) %>% nest() 
ir$Species <- as.character(ir$Species)

A tibble: 3 x 2

Species    data             
  <chr>      <list>           
1 setosa     <tibble [50 x 4]>
2 versicolor <tibble [50 x 4]>
3 virginica  <tibble [50 x 4]>

I tried the linked solution:

temp <- ir %>% purrrlyr::by_row(~write.csv(.$data, file = .$Species)) 

But receive the following error:

Error in by_row(., ~write.csv(.$data, file = .$Species)) : 
  STRING_PTR() can only be applied to a 'character', not a 'list'

I have read about purrr::walk but I can't seem to figure out how to implement it.

We could use map2

library(purrr)
map2(ir$data, ir$Species, ~ write.csv(.x, file = paste0(.y, ".csv")))

If we don't want the NULL output message on console, use iwalk

iwalk(setNames(ir$data, ir$Species), ~ write.csv(.x, file = paste0(.y, ".csv")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM