Alex Coppock
Alex Coppock

Reputation: 2252

Use group_by to create separate dataframes

I'd like to xtable groups of a dataframe separately. It seems like dplyr's group_by() is a great way to go, but I think I need a way to create separate dataframes.

in pseudocode:

library(dplyr)
by_cyl <- group_by(mtcars, cyl)
# does something like this exist?
grouped_dfs_list <- create_separate_dfs(by_cyl) 
xtable(grouped_dfs_list[[1]])
xtable(grouped_dfs_list[[2]])
xtable(grouped_dfs_list[[3]])

does something like create_separate_dfs() exist? Ideally it would return a list of dataframes, i guess.

Upvotes: 1

Views: 140

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Try split:

df = data.frame(id=rep(1:3, each=2), val=letters[1:6])
split(df, df$id)

#$`1`
#  id val
#1  1   a
#2  1   b

#$`2`
#  id val
#3  2   c
#4  2   d

#$`3`
#  id val
#5  3   e
#6  3   f

Upvotes: 3

Related Questions