场景:我有一个df,多个用户的"得分"尝试通过测试.每次观察都是尝试使用userID和得分.有些用户可能会传递他们的第一次尝试,有些可能需要几次; 他们得到无限的尝试.我想找到每个用户的平均分数.
例如:
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)
Run Code Online (Sandbox Code Playgroud)
我需要一个最终结果数据框,它只是一个唯一的用户ID列表,其中包含所有尝试的平均值(无论是尝试过一次还是多次).
在我试过的所有愚蠢的方法中,我最近的是:
avgScores = aggregate(scores, by=list("userID"), "mean")
Run Code Online (Sandbox Code Playgroud)
并收到以下错误消息:"参数必须具有相同的长度." 我也尝试过排序和子设置(实际的数据框有时间戳),摆动我的鼻子,一起敲我的鞋子,但我没有在哪里,这个noob大脑被炸.
谢谢
更好(更优雅)这里使用aggregate
公式形式:
aggregate(score~userID,scores,mean)
Run Code Online (Sandbox Code Playgroud)
或者使用您尝试过的经典表单,但结果略有不同:
aggregate(scores,by=list(userID),mean) ## using name and not string
Run Code Online (Sandbox Code Playgroud)
当然,如果你有大数据框架,最好使用其他答案中建议的解决方案之一.
归档时间: |
|
查看次数: |
126 次 |
最近记录: |