coip February 2016

Extracting a list from a column, for each group in another column

I have a data frame in long format with two factor variables as columns, with the first column representing a series of unique classes and the second column representing a grouping variable (in this case, the city where the 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
#   A     Atlanta
#   B     Atlanta
#   C     Atlanta
#   D     Detroit
#   E     Detroit
#   F     Milwaukee
#   G     Milwaukee
#   H     Milwaukee
#   I     Milwaukee
#   J     Portland
#   K     Juneau

For each city, I would like a list of all the classes that take place there. Ideally, the output would look like 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 and failed. Arguably the closest I came was via dcast, but it wasn't quite the output I was aiming for:

library(reshape2)
class.list <-dcast(samp, city ~ class)

class.list
# place       A         B         C        D        E         F    ...
# Atlanta  Atlanta   Atlanta   Atlanta    <NA>     <NA>      <NA>  ...
# Detroit    <NA>       <NA>      <NA>   Detroit   Detroit   <NA>  ...
# ...

Answers


akrun February 2016

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 another option is unstack

unstack(samp, class~city)

Post Status

Asked in February 2016
Viewed 1,218 times
Voted 5
Answered 1 times

Search




Leave an answer