首页 > 解决方案 > 合并具有不同年龄形式的两个数据框

问题描述

我有两个具有不同变量的数据框,名为“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 

标签: r

解决方案


您可以将 的年龄列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(`==`, `==`, `<=`, `>=`))  

推荐阅读