按ID分组,新表的每个元素都是一个向量 [英] Group by ID, each element of the new table is a vector
本文介绍了按ID分组,新表的每个元素都是一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的表格
data.table(ID = c ,6),
R = c(s,s,n,n,s,s),
S = c a,a,b,b,b))
<我想获得此结果
ab
s 1,2 5,6
n 3 4
在data.table中有任何选项可以做到这一点吗?
c> c> c> c> 聚合函数:
库(功能)
库(reshape2)
dcast ,R〜S,value.var ='ID',fun.aggregate = Curry(paste0,collapse =','))
#R ab
#1 n 3 4
#2 s 1,2 5,6
或者甚至缩写为@akrun下划线:
dcast(df,R〜S,value.var ='ID',toString)
I have a table like this
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"))
and I'm trying to get this result
a b
s 1, 2 5, 6
n 3 4
Is there any option in data.table can do this?
解决方案
You can use dcast
from reshape2
with the appropriate aggregating function:
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
Or even short as @akrun underlined:
dcast(df, R~S, value.var='ID', toString)
这篇关于按ID分组,新表的每个元素都是一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文