【问题标题】:Calculating mean of several values based on parameters in other columns [duplicate]根据其他列中的参数计算几个值的平均值[重复]
【发布时间】:2018-09-08 23:46:46
【问题描述】:

我有一个如下数据框:

df <- data.frame(category = c('A','B','C','A','C','B'),
                 value    = c(5.4, 5, 3.4,7.5,6.7,3.5),
                 status   = c('HC','D','D','HC','HC','D'))

我想计算类别和状态的所有组合的平均值。例如,('A','HC') 和 ('B','HC') 的一个平均值。如果只有一个值,它应该只输出那个奇异值。

如何做到这一点?

【问题讨论】:

    标签: r group-by dplyr aggregate


    【解决方案1】:

    您可以使用dplyr 或data.table 进行聚合

    require(dplyr)
    df %>% group_by(category,status) %>%
           summarize(mean_value=mean(value))
    
      category status mean_value
        <fctr> <fctr>      <dbl>
    1        A     HC       6.45
    2        B      D       4.25
    3        C      D       3.40
    4        C     HC       6.70
    

    另请参阅@PoGibas,请重新发布您的data.table 答案。

    【讨论】:

      【解决方案2】:

      这是另一种解决方案

      # defining the set of all combinations of category/statuts in df
      all.combinations <- unique(paste(df$category, df$status, sep = ";"))
      
      # creating a function that will return the mean of one given combination
      fun1 <- function(x){
        indices <- which(paste(df$category, df$status, sep = ";") == all.combinations[x])
        sigma <- mean(df$value[indices])
        return(sigma)
      }
      
      # finally applying our function to all possible combinations
      sapply(1:length(all.combinations), fun1)
      [1] 6.45 4.25 3.40 6.70
      

      【讨论】:

        猜你喜欢
        • 2014-11-04
        • 1970-01-01
        • 2021-06-07
        • 2020-04-09
        • 2020-03-03
        • 1970-01-01
        • 2018-11-03
        • 1970-01-01
        • 2020-04-18
        相关资源
        最近更新 更多