我的数据框如下所示:
x <- data.frame(c("a","a","a","a","b","b","c","c","c","a", "a"), c(1,2,3,4,1,2,1,2,3, 1, 2))
names(x) <- c("id","nr")
id nr
1 a 1
2 a 2
3 a 3
4 a 4
5 b 1
6 b 2
7 c 1
8 c 2
9 c 3
10 a 1
11 a 2
我希望有这样的东西:
id 1 2 3 4
a 1 2 3 4
a 1 2 NA NA
b 1 2 NA NA
c 1 2 3 NA
我已经使用了dcast(x, id ~ nr, value.var ="nr")
,但我收到了警告:
&#34;缺少聚合函数:默认为长度&#34;。
据我所知,这是由于非唯一行造成的。我也创建了组,它给了我上面的结果。但有没有办法创建它而无需创建组?
x <- data.frame(c("a","a","a","a","b","b","c","c","c","a", "a"),
c(1,1,1,1,1,1,1,1,1,2,2), c(1,2,3,4,1,2,1,2,3, 1, 2))
names(x) <- c("id", "group","nr")
dcast(x, id + group ~ nr, value.var = "nr")
答案 0 :(得分:4)
您可能需要分组变量。我们可以使用dcast
,然后使用data.table
的devel版本中的v1.9.5+
来尝试,而不是像示例中所示手动创建它。即library(data.table)
dcast(setDT(x)[, gr:=rleid(id)], id+gr~nr, value.var='nr')[,gr:=NULL][]
# id 1 2 3 4
#1: a 1 2 3 4
#2: a 1 2 NA NA
#3: b 1 2 NA NA
#4: c 1 2 3 NA
。安装devel版本的说明是here
dcast
或者@Arun在评论中提到,我们可以直接在dcast(setDT(x), id + rleid(id) ~ nr, value.var = 'nr')[,id_1:= NULL]
本身
for (int i=0; i<5; i++){
int[] tmp = list.get(i);
for (int j=0; j<tmp.length; j++) {
System.out.println(tmp[j]);
}
}