R - 从分组数据返回嵌套列表

时间:2016-04-01 18:21:00

标签: r data.table

我在data.table中有数据,如下所示:

#Load in example data
library(jsonlite)
library(data.table)
json<-'[{"id":"a","group":"foo","value":2.7408},{"id":"b","group":"foo","value":6.5785},{"id":"c","group":"foo","value":5.4263},{"id":"d","group":"bar","value":5.2845},{"id":"e","group":"bar","value":4.1038},{"id":"f","group":"bar","value":3.7421},{"id":"g","group":"bar","value":2.7618},{"id":"h","group":"bar","value":3.7211},{"id":"i","group":"baz","value":4.1616},{"id":"j","group":"baz","value":3.8822}]'
example<-data.table(fromJSON(json))
example

id group  value
1:  a   foo 2.7408
2:  b   foo 6.5785
3:  c   foo 5.4263
4:  d   bar 5.2845
5:  e   bar 4.1038
6:  f   bar 3.7421
7:  g   bar 2.7618
8:  h   bar 3.7211
9:  i   baz 4.1616
10:  j   baz 3.8822

我想要的是检索每个组的id的嵌套列表。我想要从组名中命名内部列表。也许一个例子可以提供清晰度:

# This is what I would like to accomplish programmatically.
# Is there a data.table way to do this? How about plyr? 
# It seems like a pretty straightforward task, so I imagine 
# there is a method for this which I don't know about.
foo<-example$id[example$group=='foo']
bar<-example$id[example$group=='bar']
baz<-example$id[example$group=='baz']
list(foo=foo,bar=bar,baz=baz)

$foo
[1] "a" "b" "c"

$bar
[1] "d" "e" "f" "g" "h"

$baz
[1] "i" "j"

提前感谢任何建议。

1 个答案:

答案 0 :(得分:1)

要保持组数据嵌套,请添加list

> example[,.(list(id)),by=group]
   group        V1
1:   foo     a,b,c
2:   bar d,e,f,g,h
3:   baz       i,j

data.table打印出带逗号的嵌套向量,因此它可能看起来像一个字符串,但V1的类型为list,列中的每个单元格都是一个向量。