r - 合并具有不同年龄形式的两个数据框
问题描述
我有两个具有不同变量的数据框,名为“df”和 df1。我想要做的是基于“性别”、“年龄”和“地区”将 df1 与“df”合并,使得“df”中的年龄获得给定的 AC 值。例如,如果 AC 位于 20-24 年龄段,则“df”中介于 20 到 24 之间的所有年龄都将获得相同的 AC 值。先感谢您。
df<-
district residence gender age weight id
1 1 1 12 26.8 1
2 2 2 14 21.4 2
3 1 1 20 24.2 3
4 2 2 23 35.8 4
5 1 1 31 42.3 5
6 2 2 16 25.2 6
7 1 1 22 35.3 7
8 2 2 45 25.3 8
9 1 1 48 36.2 9
10 2 2 39 35.5 10
df1<-
district age gender AC
1 15-19 2 0.0301
2 20-24 2 0.0934
3 25-29 2 0.108
4 30-34 2 0.0894
5 35-39 2 0.0444
6 40-44 2 0.00945
7 45-49 2 0.00226
8 15-19 2 0.0258
9 20-24 2 0.0701
10 25-29 2 0.0827
解决方案
您可以将 的年龄列df1
分成两列并使用fuzzyjoin
。
library(dplyr)
library(tidyr)
library(fuzzyjoin)
df1 %>%
separate(age, c('start', 'end'), sep = '-', convert = TRUE) %>%
fuzzy_right_join(df,
by = c('district', 'gender', 'start' = 'age', 'end' = 'age'),
match_fun = c(`==`, `==`, `<=`, `>=`))
推荐阅读
- c - 如何访问在 main 的另一个函数中创建的数组而不返回它?
- oracle - 请求的 URL /apex/apex_admin 失败
- python - 如何在 spyder 或 Jupyter 和 html 网页中显示样式的 pandas 数据框
- ckan - 在具有私有 IP 的云 vm 中安装 CKAN
- go - 上下文使用 Value(key) 后返回 nil 接口
- matlab - MATLAB 错误:“向量的长度必须相同”
- java - 随机数只有几次
- laravel - laravel 用户通过多对多关系中的角色注册
- python - 两个不同大小数组的求和乘积
- sml - 如何在 SML 中的 else if 语句中解决“未解析的弹性记录”?