2

I know the split command is the easiest way to turn a df into a list of df objects, but how can they be assigned to different (seperated) dataframes?

df.List <- split(df, df$column)
OB83
  • 476
  • 2
  • 10
  • I don't really understand your question. What is the different between a list of data.frames and different data.frames? And why you want to avoid using a list? – sgibb Sep 13 '13 at 07:58
  • Rubberduck myself! In my case, the split argument contains a long string. So calling each "subset" is hard. Renaming the subset is a better solution. nam <- c("Q1","Q2","Q3","Q4","Q5","Q6") for (i in 1:length(nam)) { assign(nam[i], df.List[[i]]) } – OB83 Sep 13 '13 at 08:03
  • 2
    Do you want to post it as an answer to help people with the same question in the future? – sgibb Sep 13 '13 at 08:04

2 Answers2

5

Look at the function list2env. Try:

list2env(split(df, df$column), envir = .GlobalEnv)
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • That would a very simple and easy solution! As mentioned, my variable contains strings, so with **list2env** they become my column names. Thanks! – OB83 Sep 13 '13 at 08:19
  • @Oblmns, sorry. I don't quite understand your comment. Perhaps if you post some sample data and an example of the output you would be looking for, I can update my answer to be more meaningful. – A5C1D2H2I1M1N2O1R2T1 Sep 13 '13 at 08:20
  • a <- c("some long text with another word", "more words in a long sentence", "this word contains multiple letters") b <- c(1,2,3) x <-data.frame(a,b) After split(x, x$a) and using list2env $a will be my df names. right? – OB83 Sep 13 '13 at 08:32
  • @Oblmns, yes, but since there are spaces in them, you'll need to access them using backticks, for example `\`more words in a long sentence\`` – A5C1D2H2I1M1N2O1R2T1 Sep 13 '13 at 08:36
1

Hereby my solution (example with the iris dataset)

two way:

list_df <- split(iris, iris$Species) #split the dataset into a list of datasets based on the value of iris$Species
list2env(list_DF, envir= .GlobalEnv) #split the list into separate datasets

one way:

list2env(split(iris, iris$Species), envir = .GlobalEnv)

Or you can assign custom names for the new datasets with a for loop:

iris_split <- split(iris, iris$Species)
new_names <- c("one", "two", "three")
for (i in 1:length(iris_split)) {
  assign(new_names[i], iris_split[[i]])
OB83
  • 476
  • 2
  • 10