'R - Using a for loop to extract and export data frames from a list generated by a split

I'm new to R, have some experience with python. I needed to split a dataframe into 42 pieces, which i did, but the result gives me a list, so now i need to extract and export each dataframe from that list. I thought of using a loop (something you would do in python, but I can't get it to work. I hope that you can help me.

num_groups = 42

lista <- RSI_SGR1702_MAYO %>% 
  group_by((row_number()-1) %/% (n()/num_groups)) %>%
  nest %>% pull(data)

# Loop
for(i in (1:42)){
  RSI_SGR[[i]] <- as.data.frame(lista[[i]])
  names(RSI_SGR[[i]]) <- paste(names(RSI_SGR1702_MAYO)) # Replace colnames
  i = i + 1
}

I know this probably isn't the correct syntax for R, but i can't find an answer. The result shoud be 42 independent dataframes stored and ready to be exported. Thanks in advance.



Solution 1:[1]

This code saves a csv file for each group as defined by your group_by() call.

library(dplyr)
library(purrr)

RSI_SGR1702_MAYO %>% 
  group_by((row_number()-1) %/% (n()/num_groups)) %>%
  group_map(function (x) write.csv(x)) %>%
  group_split() %>%
  imap(function(x, y) write.csv(x, file = paste0("file", y, ".csv")))
  

Can't test if it works, as I don't have your data. But with mocked data it works:

library(dplyr)
library(purrr)
tibble(a = sample(1:5, 15, replace = TRUE),
       b = sample(letters, 15)) |> 
  group_by(a) |> 
  group_split() |> 
  imap(function(x, y) write.csv(x, file = paste0("file", y, ".csv")))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1