【发布时间】:2016-04-01 18:21:00
【问题描述】:
我在 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"
提前感谢您的任何建议。
【问题讨论】:
-
试试
split(example$id,example$group)。 -
完美!谢谢你。我显然还有很多功能要学。
标签: r data.table