I’m trying to create separate data.frame objects based on levels of a factor. So if I have:
df <- data.frame(
x=rnorm(25),
y=rnorm(25),
g=rep(factor(LETTERS[1:5]), 5)
)
How can I split df into separate data.frames for each level of g containing the corresponding x and y values? I can get most of the way there using split(df, df$g), but I’d like the each level of the factor to have its own data.frame.
What’s the best way to do this?
I think that
splitdoes exactly what you want.Notice that X is a list of data frames, as seen by
str:If you want individual object with the group g names you could assign the elements of X from
splitto objects of those names, though this seems like extra work when you can just index the data frames from the listsplitcreates.Edit Or even better than using
lapplyto assign to the global environment uselist2env: