每个受访者平均未知数量的回复; R

average an unknown number of responses per respondent; R

场景:我有一个 df,"scores" 多个用户尝试通过测试。每个观察都是对用户 ID 和分数的尝试。有些用户可能会通过他们的第一次尝试,有些可能需要多次;他们得到无限的尝试。我想找到每个用户的平均分数。

例如:

userID = c(1:20, sample(1:20, 10, replace = TRUE))
score = c(rnorm(15, mean = 60, sd = 10), rnorm(8, mean = 70, sd = 5), 
rnorm(7, mean = 90, sd = 2))
scores = data.frame(userID, score)

我需要一个最终结果数据框,它只是一个唯一用户 ID 的列表以及他们所有尝试的平均值(无论他们尝试一次还是多次)。

在我尝试过的所有愚蠢方法中,我最近尝试的是:

avgScores = aggregate(scores, by=list("userID"), "mean")

并收到以下错误消息:"arguments must have same length." 我也试过排序和子设置(实际数据帧有时间戳),扭动鼻子和敲击我的鞋子,但我不知道在哪里,这个菜鸟的大脑被炸了。

谢谢你

#data.table
library(data.table)
DT<-data.table(scores)
DT[,.(mean_score=mean(score)),by=userID]

#dplyr
library(dplyr)
scores %>%
group_by(userID)%>%
summarise(mean_score=mean(score))

你可以这样做:

library(dplyr)
scores %>% group_by(userID) %>% summarise(mean = mean(score))

更好(更优雅)在这里使用 aggregate 和公式形式:

aggregate(score~userID,scores,mean)

或者使用您尝试过的经典形式,但您得到的结果略有不同:

aggregate(scores,by=list(userID),mean) ## using name and not string

当然,如果你有大 data.frame ,最好使用其他答案中建议的解决方案之一。