0

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.

Conrad
  • 1
  • 1
    Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by sharing the data you are using and including all `library()` commands you are using to load packages. – Till Feb 18 '22 at 19:09

1 Answers1

0

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")))
Till
  • 3,845
  • 1
  • 11
  • 18