假设我有以下内容data.table
:
dt <- data.table(id = c(rep(1, 5), rep(2, 4)),
sex = c(rep("H", 5), rep("F", 4)),
fruit = c("apple", "tomato", "apple", "apple", "orange", "apple", "apple", "tomato", "tomato"),
key = "id")
id sex fruit
1: 1 H apple
2: 1 H tomato
3: 1 H apple
4: 1 H apple
5: 1 H orange
6: 2 F apple
7: 2 F apple
8: 2 F tomato
9: 2 F tomato
id
每行代表某人(由它和标识sex
)吃了 a的事实fruit
。我想数一下每个fruit
人被吃掉的次数sex
。我可以这样做:
dt[ , .N, by = c("fruit", "sex")]
这使:
fruit sex N
1: apple H 3
2: tomato H 1
3: orange H 1
4: apple F 2
5: tomato F 2
问题是,通过这种方式,我失去了orange
for的计数sex == "F"
,因为这个计数是 0。有没有办法在不丢失零计数组合的情况下进行这种聚合?
非常清楚,期望的结果如下:
fruit sex N
1: apple H 3
2: tomato H 1
3: orange H 1
4: apple F 2
5: tomato F 2
6: orange F 0
非常感谢 !