按组折叠并使用R在data.frame中计算n

use*_*032 2 r

我有一个包含三个变量的数据框:治疗,剂量和结果(加或减).我对每种治疗和剂量都有多个观察结果.我正在尝试输出一个列联数据表,该数据表会使数据崩溃,以指示每个结果的数量与治疗和剂量以及观察次数的函数关系.例如:

treatment dose outcome    
control 0 0
control 0 0
control 0 0
control 0 1
treatmentA 1 0
treatmentA 1 1
treatmentA 1 1
treatmentA 2 1
treatmentA 2 1 
treatmentA 2 1
Run Code Online (Sandbox Code Playgroud)

期望的输出是:

treatment dose outcome n
control 0 0 1 4
treatmentA 1 2 3
treatmentA 2 3 3
Run Code Online (Sandbox Code Playgroud)

我整天都玩这个,并且除了能够获得每个观察结果的每个结果的频率之外没有多少运气.任何建议将被赞赏(包括指出R手册和/或示例的哪些部分)我忽略了.

谢谢!

[R

Vic*_* K. 5

这是一个使用精彩包装的解决方案data.table:

library(data.table)
x <- data.table(read.table( text = "treatment dose outcome    
control 0 0
control 0 0
control 0 0
control 0 1
treatmentA 1 0
treatmentA 1 1
treatmentA 1 1
treatmentA 2 1
treatmentA 2 1 
treatmentA 2 1", header = TRUE)
x[, list(outcome = sum(outcome), count = .N), by = 'treatment,dose']
Run Code Online (Sandbox Code Playgroud)

产生

    treatment dose outcome count
1:    control    0       1     4
2: treatmentA    1       2     3
3: treatmentA    2       3     3
Run Code Online (Sandbox Code Playgroud)