这是一个基本问题,但我很难过:
我有以下 R 数据表:
library(data.table)
DT <- fread('unique_point biased data_points team groupID
up1 FALSE 3 A xy28352
up1 TRUE 4 A xy28352
up2 FALSE 1 A xy28352
up2 TRUE 0 X xy28352
up3 FALSE 12 Y xy28352
up3 TRUE 35 Z xy28352')
打印为
> DT
unique_point biased data_points team groupID
1: up1 FALSE 3 A xy28352
2: up1 TRUE 4 A xy28352
3: up2 FALSE 1 A xy28352
4: up2 TRUE 0 X xy28352
5: up3 FALSE 12 Y xy28352
6: up3 TRUE 35 Z xy28352
该列的值team是字母 A 到 Z,26 种可能性。在这一刻。如果我用这段代码计算行值:
DT[, counts := .N, by=c("team")]
这使
> DT
unique_point biased data_points team groupID counts
1: up1 FALSE 3 A xy28352 3
2: up1 TRUE 4 A xy28352 3
3: up2 FALSE 1 A xy28352 3
4: up2 TRUE 0 X xy28352 1
5: up3 FALSE 12 Y xy28352 1
6: up3 TRUE 35 Z xy28352 1
我想创建 26 个新列,DT其中给出每个team, A, B,C等的大小。
生成的 data.table 如下所示:
> DT
unique_point biased data_points team groupID A B C ... Z
1: up1 FALSE 3 A xy28352 3 0 0 ... 1
2: up1 TRUE 4 A xy28352 3 0 0 ... 1
3: up2 FALSE 1 A xy28352 3 0 0 ... 1
4: up2 TRUE 0 X xy28352 3 0 0 ... 1
5: up3 FALSE 12 Y xy28352 3 0 0 ... 1
6: up3 TRUE 35 Z xy28352 3 0 0 ... 1
我不确定如何用data.table语法做到这一点..
编辑:我也很高兴使用 base R 和 dplyr 来做到这一点。