【问题标题】:average an unknown number of responses per respondent; R [duplicate]平均每个受访者的未知数量的响应; R [重复]
【发布时间】:2015-05-08 15:43:54
【问题描述】:

场景:我有一个 df,多个用户尝试通过测试的“分数”。每个观察都是对用户 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")

并收到以下错误消息:“参数必须具有相同的长度。” 我也尝试过排序和子设置(实际的数据框有时间戳),然后扭动我的鼻子,一起敲打我的鞋子,但是我什么地方都没有,这个菜鸟的大脑被炸了。

谢谢你

【问题讨论】:

    标签: r split aggregate


    【解决方案1】:
    #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))
    

    【讨论】:

    • 从未考虑过 data.table 方法,所以我将不得不使用它以及 dplyr。感谢您的帮助!
    【解决方案2】:

    你可以这样做:

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

    【讨论】:

    • 也有效,我很欣赏不同的方法。谢谢!
    【解决方案3】:

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

    aggregate(score~userID,scores,mean)
    

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多