从列中提取列表,为另一列中的每个组提取列表

时间:2016-02-08 15:39:12

标签: r list aggregation reshape2

我有一个长格式的数据框,有两个因子变量作为列,第一列代表一系列唯一类,第二列代表分组变量(在这种情况下,是发生类的城市)。

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

对于每个城市,我想要列出那里发生的所有课程。理想情况下,输出看起来像这样:

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"

我尝试了各种解决方案但都失败了。可以说我最接近的是通过dcast,但它并不是我想要的输出:

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>  ...
# ...

1 个答案:

答案 0 :(得分:3)

我们可以使用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"

或另一个选项是unstack

unstack(samp, class~city)