Reputation: 399
I have a dataframe such as
id <- c(1,1,1,2,2,3,3,3,3)
element <- c(25122,356,4454,5432,342340,12443,12354,123536,234134)
df <- data.frame(id = as.factor(id), element)
I would like to create a list of the id
groups with their corresponding element
s such as:
dflist <- list(c(25122,356,4454), c(5432,342340), c(12443,12354,123536,234134))
Upvotes: 3
Views: 57
Reputation: 47300
Here's a solution with tapply:
library(magrittr)
df %$% tapply(element,id,list)
(elements are named with id, add %>% unname
if it's an issue)
Upvotes: 1
Reputation: 887048
We can use split
unname(split(df$element, df$id))
Or with unstack
unname(unstack(df, element ~id))
Upvotes: 4