首页 > 解决方案 > 在R中按组计算平均年龄

问题描述

我有以下数据:https ://raw.githubusercontent.com/fivethirtyeight/data/master/congress-age/congress-terms.csv

我正在尝试确定如何计算每个党派(共和党和民主党)的国会议员的平均年龄(任期开始)。

我希望对如何去做这件事有一些帮助。我是 R 的初学者,我只是在玩数据。

谢谢!

标签: raveragemean

解决方案


试试这个方法。为所需的各方进行过滤,然后进行总结。之后,您可以重塑为宽,以便在每个单独的日期都有双方。这里使用tidyverse函数的代码:

library(dplyr)
library(tidyr)
#Data
df <- read.csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/congress-age/congress-terms.csv',stringsAsFactors = F)
#Code
newdf <- df %>% filter(party %in% c('R','D')) %>%
  group_by(termstart,party) %>% summarise(MeanAge=mean(age,na.rm=T)) %>%
  pivot_wider(names_from = party,values_from=MeanAge)

输出:

# A tibble: 34 x 3
# Groups:   termstart [34]
   termstart      D     R
   <chr>      <dbl> <dbl>
 1 1947-01-03  52.0  53.0
 2 1949-01-03  51.4  54.6
 3 1951-01-03  52.3  54.3
 4 1953-01-03  52.3  54.1
 5 1955-01-05  52.3  54.7
 6 1957-01-03  53.2  55.4
 7 1959-01-07  52.4  54.7
 8 1961-01-03  53.4  53.9
 9 1963-01-09  53.3  52.6
10 1965-01-04  52.3  52.2
# ... with 24 more rows

推荐阅读