【问题标题】:How to get the average (or sum, count, etc.) of variables for each group ID? [duplicate]如何获得每个组 ID 的变量的平均值(或总和、计数等)? [复制]
【发布时间】:2017-07-25 21:01:16
【问题描述】:

我有一个包含 ID 列表和其他变量的数据框,如下所示:

Student_ID       Score
6                94
2                63
6                100
7                44
6                97
2                67

我想创建另一个仅包含 Student_ID 和平均分数的数据框,如下所示:

Student_ID       Avg_Score
2                65
6                97
7                44 

当然,实际的数据集要大得多。

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    你可以使用dplyr包:

    df %>% group_by(Student_ID) %>% summarise(Avg_Score = mean(Score))
    
    
    # # A tibble: 3 x 2 
    #   Student_ID Avg_Score 
    #        <int>     <dbl> 
    # 1          2        65 
    # 2          6        97 
    # 3          7        44
    

    您也可以在基础 R 中使用aggregate

    aggregate( Score ~ Student_ID, df, mean) #column name will remain as "Score"
    
    #   Student_ID Score 
    # 1          2    65 
    # 2          6    97 
    # 3          7    44
    

    【讨论】:

    • 您可以将mean替换为sumcount或其他函数。
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2017-04-16
    相关资源
    最近更新 更多