【问题标题】:Add variable with summarise but keep all other variables in R使用汇总添加变量,但将所有其他变量保留在 R 中
【发布时间】:2020-04-29 09:25:36
【问题描述】:

我有一个数据集,其中包含向不同政客捐款的数据,其中每一行都是特定的捐款。

donor.sector <- c(sector A, sector B, sector X, sector A, sector B)
total <- c(100, 100, 150, 125, 500)
year <- c(2006, 2006, 2007, 2007, 2007)
state <- c(CA, CA, CA, NY, WA)
target_specific <- c(politician A, politician A, politician A, politician B, politician C)
dat <- as.data.frame(donor.sector, total, year, target_specific, state)

我正在尝试计算每位政治家一年的捐款平均值。我可以通过以下方式做到这一点:

library(dplyr)
  new.df <- dat%>%
  group_by(target_specific, year)%>%
  summarise(mean= mean(total))

我的问题是,由于我对此进行了分组,因此结果只有三个变量:平均值、年份和特定目标。有没有办法可以做到这一点并创建一个新的数据框,在其中保留政治级别的变量,例如州?

非常感谢!

【问题讨论】:

    标签: r merge dplyr summarize


    【解决方案1】:

    有两种方法可以做到这一点:

    group_by 中包含附加变量:

    library(dplyr)
    
    dat%>%
       group_by(target_specific, year, state)%>%
       summarise(mean= mean(total))
    
    #  target_specific  year state  mean
    #  <chr>           <dbl> <chr> <dbl>
    #1 politician A     2006 CA      100
    #2 politician A     2007 CA      150
    #3 politician B     2007 NY      125
    #4 politician C     2007 WA      500
    

    或者保持相同的group_by 结构,您可以包含附加变量的first 值。

    dat%>%
      group_by(target_specific, year)%>%
      summarise(mean= mean(total), state = first(state))
    

    【讨论】:

      【解决方案2】:

      base R中,我们可以使用aggregate

      aggregate(total ~ ., subset(data, select = -donor.sector), mean)
      

      【讨论】:

        猜你喜欢
        • 2019-08-18
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 1970-01-01
        • 2020-05-25
        • 2021-11-16
        • 2017-01-08
        • 2018-11-14
        相关资源
        最近更新 更多