【问题标题】:Mean per group and range [duplicate]每组和范围的平均值[重复]
【发布时间】:2016-07-26 03:00:08
【问题描述】:

我不明白如何解决这个问题。谁能帮我解决这个问题。

我有如下的data.frame

Gender  Age  BMI
Male     20  18
Male     40  22
Female   30  19
Male     50  24
Female   28  21

我想得到如下的data.frame

Age Range  Male-BMI-Average  Female-BMI-Average
0-25        ###                  ###
26-50       ###                  ###   

我尝试使用 cut 和 dcast 但我不明白如何获得年龄范围内不同性别组的平均值?

【问题讨论】:

  • 最短的方法是:你暴露你的努力和可能的错误,如果需要的话,SO会提出一些建议。
  • 我可以通过以下方式解决问题。 Step1:子集 MaleData Step2:在 MaleData 上使用 CUT Step3:在 MaleData 的 BMI 上进行聚合 Step4:在 FemaleData 上重复 step1-step3 Step5:将它们合并到一个 DataFrame 中

标签: r


【解决方案1】:

我们可以使用cut 创建“AgeRange”,然后使用dcastdata.table 将其转换为“宽”格式,这在data.table 中更容易,因为dcastfun.aggregate (这里我们指定为mean)。

library(data.table)
dcast(setDT(df1)[, AgeRange := cut(Age, breaks = c(0, 25, 50), 
                labels = c("0-25", "26-50"))], 
                AgeRange~Gender, value.var = "BMI", mean)
#   AgeRange Female Male
#1:   0-25    NaN   18
#2:  26-50     20   23

或者使用dplyr,我们可以通过cut创建的'AgeRange'和summarise与'BMI'的mean分组,对应于'性别'中的'男性'和'女性'列。

library(dplyr)
df1 %>%
    group_by(AgeRange = cut(Age, breaks = c(0, 25, 50), 
                       labels = c("0-25", "26-50"))) %>%
    summarise(Male_BMI_Avg = mean(BMI[Gender=="Male"]), 
              Female_BMI_Avg = mean(BMI[Gender=="Female"]))
#  AgeRange Male_BMI_Avg Female_BMI_Avg
#    <fctr>        <dbl>          <dbl>
#1     0-25           18            NaN
#2    26-50           23             20

【讨论】:

    【解决方案2】:

    这是一个使用 dplyr 和 reshape2 包的解决方案:

    #Your Data
    df<-read.table(header = TRUE, text="Gender  Age  BMI
    Male     20  18
                   Male     40  22
                   Female   30  19
                   Male     50  24
                   Female   28  21")
    
    
    library(dplyr)
    results<-summarize(group_by(df, Gender, cut(df$Age, breaks=c(0, 25, 50))), mean(BMI))
    library(reshape2)
    names(results)<-c("Gender", "Age", "mean-BMI")
    dcast(results, Age~Gender)
    

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多