首页 文章

使用dplyr汇总值并在数据框中存储为向量?

提问于
浏览
1

我有一个简单的data.frame,如下所示:

Group     Person  Score_1   Score_2   Score_3
1         1       90        80        79
1         2       74        83        28
1         3       74        94        89
2         1       33         9         8
2         2       94        32        78
2         3       50        90        87

我首先需要找到Score_1的平均值,在群组内的人群中崩溃(即,第1组的Score_1意思,第2组的Score_1意思等),然后我需要在所有组中崩溃到找到Score_1的平均值 . 如何计算这些值并将它们存储为单个对象?我在dplyr中使用了“summarize”函数,代码如下:

summarise(group_by(data,Group),mean(bias,na.rm=TRUE))

我想最终创建一个第6列,给出每个组的人员重复的平均值,然后是第7列,给出所有组的平均值 .

我确信还有其他方法可以做到这一点,我愿意接受建议(虽然我仍然想知道如何在dplyr中做到这一点) . 谢谢!

3 回答

  • 1

    data.table 适合这样的任务:

    library(data.table)
    
    dt <- read.table(text = "Group     Person  Score_1   Score_2   Score_3
               1         1       90        80        79
               1         2       74        83        28
               1         3       74        94        89
               2         1       33         9         8
               2         2       94        32        78
               2         3       50        90        87", header = T)
    
    dt <- data.table(dt)
    
    # Mean by group
    dt[, score.1.mean.by.group := mean(Score_1), by = .(Group)]
    # Grand mean
    dt[, score.1.mean := mean(Score_1)]
    dt
    
  • 2

    @akrun你只是吹了我的脑海!

    只是为了澄清你说的话,这是我的解释:

    library(plyr)
    
    Group <- c(1,1,1,2,2,2)
    Person <- c(1,2,3,1,2,3)
    Score_1 <- c(90,74,74,33,94,50)
    Score_2 <- c(80,83,94,9,32,90)
    Score_3 <- c(79,28,89,8,78,87)
    
    df <- data.frame(cbind(Group, Person, Score_1, Score_2, Score_3))
    
    df2 <- ddply(df, .(Group), mutate, meanScore = mean(Score_1, na.rm=T))
    mutate(df2, meanScoreAll=mean(meanScore))
    
  • 0

    要创建列,我们使用 mutate 而不是 summarise . 我们获得了平均值( MeanScore1 ),然后按'Group'分组,按组('MeanScorebyGroup')获取 mean ,最后使用 select 对列进行排序

    library(dplyr)
    df1 %>% 
        mutate(MeanScore1 = mean(Score_1)) %>%
        group_by(Group) %>% 
        mutate(MeanScorebyGroup = mean(Score_1)) %>%
        select(1:5, 7, 6)
    

    但是,这也可以使用 base R 以简单的方式完成

    df1$MeanScorebyGroup <- with(df1, ave(Score_1, Group))
    df1$MeanScore1 <- mean(df1$Score_1)
    

相关问题