按ID分组,new table的每个元素都是一个vector

Group by ID, each element of the new table is a vector

我有一个table这样的

data.table(ID = c(1,2,3,4,5,6), 
         R = c("s","s","n","n","s","s"), 
         S = c("a","a","a","b","b","b"))

我正在努力得到这个结果

      a     b
s   1, 2      5, 6
n     3         4

data.table中有没有选项可以做到这一点?

你可以试试:

library(dplyr)
library(tidyr)

df %>% 
  group_by(R, S) %>% 
  summarise(i = toString(ID)) %>% 
  spread(S, i) 

给出:

#Source: local data table [2 x 3]
#Groups: 
#
#  R    a    b
#1 n    3    4
#2 s 1, 2 5, 6

注意:这会将结果存储在一个字符串中。如果你想要一个更方便的格式来访问元素,你可以存储在一个列表中:

df2 <- df %>% 
  group_by(R, S) %>% 
  summarise(i = list(ID)) %>% 
  spread(S, i)  

给出:

#Source: local data table [2 x 3]
#Groups: 
#
#  R        a        b
#1 n <dbl[1]> <dbl[1]>
#2 s <dbl[2]> <dbl[2]>

然后您可以通过以下方式访问元素:

> df2$a[[2]][2]
#[1] "2"

您可以将 reshape2 中的 dcast 与适当的聚合函数一起使用:

library(functional)
library(reshape2)

dcast(df, R~S, value.var='ID', fun.aggregate=Curry(paste0, collapse=','))
#  R   a   b
#1 n   3   4
#2 s 1,2 5,6

或者像@akrun 下划线一样简短:

dcast(df, R~S, value.var='ID', toString)

这是一个使用普通旧 data.table 语法的替代方法:

DT[,lapply(split(ID,S),list),by=R]

# or...

DT[,lapply(split(ID,S),toString),by=R]