使用总和和计数将数据从长到长重新整形

Geo*_*nza 6 r

我试图在R中重新设置从长格式到宽格式的数据.我想通过ID得到一个类型变量的出现次数,并val通过ID和类型得到第二个变量()的值的总和,如下例所示.

我能够找到重塑计数或总和的答案,但不能同时进行.

这是原始示例数据:

> df <- data.frame(id = c(1, 1, 1, 2, 2, 2),
+                  type = c("A", "A", "B", "A", "B", "C"),
+                  val = c(0, 1, 2, 0, 0, 4))
> df
  id type val
1  1    A   0
2  1    A   1
3  1    B   2
4  2    A   0
5  2    B   0
6  2    C   4
Run Code Online (Sandbox Code Playgroud)

我想获得的输出如下:

  id A.count B.count C.count A.sum B.sum C.sum
1  1       2       1       0     1     2     0
2  2       1       1       1     0     0     4
Run Code Online (Sandbox Code Playgroud)

其中count列显示类型A,B和C的出现次数,列显示按类型sum列出的值的总和.

为了实现计数,我可以按照本答案中的建议使用reshape2::dcast默认聚合函数length:

> require(reshape2)
> df.c <- dcast(df, id ~ type, value.var = "type", fun.aggregate = length)
> df.c
  id A B C
1  1 2 1 0
2  2 1 1 1
Run Code Online (Sandbox Code Playgroud)

同样,如本回答所示,我也可以使用sums作为输出执行重新整形,这次使用sum聚合函数dcast:

> df.s <- dcast(df, id ~ type, value.var = "val", fun.aggregate = sum)
> df.s
  id A B C
1  1 1 2 0
2  2 0 0 4
Run Code Online (Sandbox Code Playgroud)

我可以将两者合并:

> merge(x = df.c, y = df.s, by = "id", all = TRUE)
  id A.x B.x C.x A.y B.y C.y
1  1   2   1   0   1   2   0
2  2   1   1   1   0   0   4
Run Code Online (Sandbox Code Playgroud)

但有没有一种方法可以一次性完成(不一定是dcastreshape2)?

phi*_*ver 5

从data.table v1.9.6开始,可以通过提供多个fun.aggregate函数来转换多个value.var列并进行转换.见下文:

library(data.table)

df <- data.table(df)
dcast(df, id ~ type, fun = list(length, sum), value.var = c("val"))
   id val_length_A val_length_B val_length_C val_sum_A val_sum_B val_sum_C
1:  1            2            1            0         1         2         0
2:  2            1            1            1         0         0         4
Run Code Online (Sandbox Code Playgroud)