r - 在R中按组计算平均年龄
问题描述
我有以下数据:https ://raw.githubusercontent.com/fivethirtyeight/data/master/congress-age/congress-terms.csv
我正在尝试确定如何计算每个党派(共和党和民主党)的国会议员的平均年龄(任期开始)。
我希望对如何去做这件事有一些帮助。我是 R 的初学者,我只是在玩数据。
谢谢!
解决方案
试试这个方法。为所需的各方进行过滤,然后进行总结。之后,您可以重塑为宽,以便在每个单独的日期都有双方。这里使用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
推荐阅读
- c++11 - std::map 如何在 C++ 中使用自定义比较函数(或调用频率)?
- c++ - 如何制作一个用 RAII 封装线程的超类
- c# - 为什么内部字段比抽象类中的受保护字段更可取?
- django - 经理对象没有属性“get_by_natural_key”
- java - android 项目构建失败并出现异常。无法获取 Gradle 包装器属性
- javascript - 在 Shopify 中触发微调器数量按钮
- python - 清理 Docker pip install 导致错误:这些包与需求文件中的哈希不匹配
- tensorflow - Google Colab 中的 TensorFlow 版本选择
- rust - 如何快速从 HashSet 中查看任意值?
- ios - Swift 和 ZoomSDK,加入会议