0

This is a follow up on this quesiton: split into multiple subset of dataframes with dplyr:group_by? .

Reproducible example:

test <- data.frame(a = c(1,1,1,2,2,2,3,3,3), b = c(1:9))

I'm interested on how to save the dataframes from the following output:

 test %>%
  group_by(a) %>%
  nest() %>%
  select(data) %>%
  unlist(recursive = F)

as separate dataframes in the environment ? The desired output is the following:

data1 <- data.frame(a = c(1,1,1), b = c(1:3))
data2 <- data.frame(a = c(2,2,2), b = c(4:6))
data3 <- data.frame(a = c(3,3,3), b = c(7:9))

There are many groups so automation is required giving: data1,data2,data3, ... data(n) dataframes.

adl
  • 1,390
  • 16
  • 36
  • 2
    Put them in a list: `myList <- split(dat, dat$a)`. See gregor's answer [here](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) as why this is a good idea. If you must have them as separate data.frames, you can use `list2env`. – lmo Jun 11 '18 at 11:42
  • @Imo Thank you for you comment but I need separate dataframes if it is possible – adl Jun 11 '18 at 11:43

1 Answers1

1

If you want the dataframe names to be created automatically as well, you could try something like this.

test <- data.frame(a = c(1,1,1,2,2,2,3,3,3), b = c(1:9))
test

n <- length(unique(test$a))

eval(parse(text = paste0("data", seq(1:n), " <- ", split(test, test$a))))
eval(parse(text = paste0("data", seq(1:n), " <-  as.data.frame(data", seq(1:3), ")"))) 
Lennyy
  • 5,932
  • 2
  • 10
  • 23