Laura
Laura

Reputation: 13

Saving multiple data frames in a for loop as separate CSV

I'm trying to save several (>600) tibbles/dataframes as CSVs in a for loop. The reason I want to save them separately is because they have different sizes columns&rows. Unfortunately it is not working. It doesn't matter whether they are a dataframe a tibble I will get the same error.

I've also tried write.csv but that does not save the actual dataframe. Instead it creates a CSV with just the word 'events355486' in the first cell. Are there any R wizards out there that could help me?

Example code here:

library(tidyverse)
match_id_test <- tibble( match_id = c(355486, 487627, 793011, 
                                       845722, 949077, 1022888),
                          game_id  = c("game355486", "game487627","game793011", 
                                       "game845722", "game949077", "game1022888"),
                          events_id = c("events355486", "events487627","events793011", 
                                        "events845722", "events949077", "events1022888")
                          )
events355486 <- tibble(x = 1:1, y= 1:1)
events487627 <- tibble(x = 1:2, y= 1:2)
events793011 <- tibble(x = 1:3, y= 1:3)
events845722 <- tibble(x = 1:4, y= 1:4)
events949077 <- tibble(x = 1:5, y= 1:5)
events1022888 <- tibble(x = 1:6, y= 1:6)
for (i in 1:nrow(match_id_test)){
    write_csv(paste0("events", match_id_test[i,1]),
              here(paste0("./Data/Events",match_id_test[i,1], ".csv")
              )
    )
}
#> Error in write_delim(x, path, delim = ",", na = na, append = append, col_names = col_names, : is.data.frame(x) is not TRUE

Upvotes: 0

Views: 491

Answers (3)

c_j_fairfield
c_j_fairfield

Reputation: 208

Using the purrr package as described by Ronak but with map2 and using readr functions this works:

map2(match_id_test$events_id,
     match_id_test$match_id,
    function(x, y){
      get(x) %>% 
        write_csv(
          here::here(
            paste0(
              "./Data/Events", y, ".csv"
            )))
    })

Upvotes: 0

Edward
Edward

Reputation: 19219

Maybe this:

for (i in 1:nrow(match_id_test)){
  write_csv(get(paste0("events", match_id_test[i,1])),
            paste0("./Data/Events", match_id_test[i,1], ".csv")
  )
}

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

With lapply, you can try :

lapply(match_id_test$events_id, function(x) 
       write.csv(get(x), paste0('./Data/Events/', x, '.csv'), row.names = FALSE))

Or using mget with purrr:imap

purrr::imap(mget(match_id_test$events_id), 
       ~write.csv(x, paste0('./Data/Events/', .y, ".csv"), row.names = FALSE))

Upvotes: 1

Related Questions