I am trying to convert a data frame:
df <- data.frame(id=c(1,1,1,2,2), code=c("a","b","c","a","b"))
to this output list where the name of each list contains the row id.
a_list <- list(
Tr1 = c("a","b","c"),
Tr2 = c("a","b")
)
Thank you!
CodePudding user response:
if not interested in names:
unstack(df, code~id)
$`1`
[1] "a" "b" "c"
$`2`
[1] "a" "b
or even:
unstack(rev(df))
$`1`
[1] "a" "b" "c"
$`2`
[1] "a" "b"
with(df, split(code, id))
$`1`
[1] "a" "b" "c"
$`2`
[1] "a" "b"
if interested in names:
unstack(transform(df, id=paste0('Tr', id)), code~id)
$Tr1
[1] "a" "b" "c"
$Tr2
[1] "a" "b"
or even:
with(df, split(code, paste0('Tr', id)))
$Tr1
[1] "a" "b" "c"
$Tr2
[1] "a" "b"
CodePudding user response:
You can use split
, i.e.
l1 <- split(df$code, df$id)
setNames(l1, paste0('Tr', seq_along(l1)))
$Tr1
[1] "a" "b" "c"
$Tr2
[1] "a" "b"