我有一个问题要计算相同ID号下的费用。
这是样本数据集d:

id answer
1   1
1   0
1   0
1   1
1   1
1   1
1   0
2   0
2   0
2   0
3   1
3   0

理想的输出是
id  rate          freq
1   4/7 (=0.5714)  7
2   0              3
3   1/2 (=0.5)     2

谢谢。

最佳答案

尝试

library(data.table)
setDT(df1)[,list(rate= mean(answer), freq=.N) ,id]
#   id      rate freq
#1:  1 0.5714286    7
#2:  2 0.0000000    3
#3:  3 0.5000000    2

要么
library(dplyr)
 df1 %>%
    group_by(id) %>%
    summarise(rate=mean(answer), freq=n())

数据
df1 <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L), answer = c(1L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 1L,
0L)), .Names = c("id", "answer"), class = "data.frame",
row.names = c(NA, -12L))

关于r - 用R计算相同的比率,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29519346/

10-10 20:17