Splitting into separate dataframes based on factor levels

I have a dataset that includes a factor with lots of levels, and I would like to filter the dataset by this factor to create new dataframes, naming each new dataframe according to the factor level that it comes from.

At the moment, I'm doing this like this:

setosa <- filter(iris, Species == "setosa")
versicolor <- filter(iris, Species == "versicolor")
virginica <- filter(iris, Species == "virginica")

This works, but my actual data has a lot more levels than iris$Species, so it quickly becomes unwieldy. Does anyone know a better way to do this? I've tried using group_split(), which is close, but doesn't quite do what I'd like - rather than a list of tibbles, I'd like each one to be saved as separate dataframe and named accordingly, as above.

Any help much appreciated!

use attach to make a list of data.frames accessible 'as if it were' in your global environment


(iris_split <- split(iris,iris$Species))



That's just what I needed, thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.