Display weighted mean by group in the data.frame

后端 未结 3 1415
一整个雨季
一整个雨季 2020-11-29 10:25

Issues regarding the command by and weighted.mean already exist but none was able to help solving my problem. I am new to R and am more used to dat

3条回答
  •  悲&欢浪女
    2020-11-29 11:15

    Try using the dplyr package as follows:

    df <- read.table(text = 'obs income education weight   
                              1   1000      A       10     
                              2   2000      B        1     
                              3   1500      B        5     
                              4   2000      A        2', 
                     header = TRUE)     
    
    library(dplyr)
    
    df_summary <- 
      df %>% 
      group_by(education) %>% 
      summarise(weighted_income = weighted.mean(income, weight))
    
    df_summary
    # education weighted_income
    #     A        1166.667
    #     B        1583.333
    
    df_final <- left_join(df, df_summary, by = 'education')
    
    df_final
    # obs income education weight weighted_income
    #  1   1000         A     10        1166.667
    #  2   2000         B      1        1583.333
    #  3   1500         B      5        1583.333
    #  4   2000         A      2        1166.667
    

提交回复
热议问题