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,046
  • 6
  • 26

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
  • 4,953
  • 2
  • 7
  • 21