r - Extracting a list from a column, for each group in another column -
i have data frame in long format 2 factor variables columns, first column representing series of unique classes , second column representing grouping variable (in case, city class takes place).
class <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k") city <- c("atlanta", "atlanta", "atlanta", "detroit", "detroit", "milwaukee", "milwaukee", "milwaukee", "milwaukee", "portland", "juneau") samp <- data.frame(class, city) samp # class city # atlanta # b atlanta # c atlanta # d detroit # e detroit # f milwaukee # g milwaukee # h milwaukee # milwaukee # j portland # k juneau
for each city, list of classes take place there. ideally, output this:
class.list <- list(atlanta = c("a", "b", "c"), detroit = c("d", "e"), milwaukee = c("f", "g", "h", "i"), portland = "j", juneau = "k") class.list # $atlanta # [1] "a" "b" "c" # # $detroit # [1] "d" "e" # # $milwaukee # [1] "f" "g" "h" "i" # # $portland # [1] "j" # # $juneau # [1] "k"
i've tried various solutions , failed. arguably closest came via dcast
, wasn't quite output aiming for:
library(reshape2) class.list <-dcast(samp, city ~ class) class.list # place b c d e f ... # atlanta atlanta atlanta atlanta <na> <na> <na> ... # detroit <na> <na> <na> detroit detroit <na> ... # ...
we can use split
split(as.character(samp$class), samp$city) #$atlanta #[1] "a" "b" "c" #$detroit #[1] "d" "e" #$juneau #[1] "k" #$milwaukee #[1] "f" "g" "h" "i" #$portland #[1] "j"
or option unstack
unstack(samp, class~city)
Comments
Post a Comment