且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在多列上执行左联接,其中之一是部分字符串

更新时间:2023-11-28 19:21:40

这个怎么样?

library(dplyr)

df1 %>%
  mutate(first_name_1st2char = substr(first_name, 1, 2)) %>%
  left_join(df2 %>% mutate(first_name_1st2char = substr(first_name, 1, 2)), 
            by = c("first_name_1st2char", "last_name", "year")) %>%
  select(-first_name_1st2char)

输出为:

  first_name.x last_name year first_name.y age
1         john      asdf 2018          joe  12
2         jack    qwerty 2017         jake  34

样本数据:

df1 <- structure(list(first_name = structure(c(2L, 1L), .Label = c("jack", 
"john"), class = "factor"), last_name = structure(1:2, .Label = c("asdf", 
"qwerty"), class = "factor"), year = c(2018, 2017)), .Names = c("first_name", 
"last_name", "year"), row.names = c(NA, -2L), class = "data.frame")

df2 <- structure(list(first_name = structure(c(3L, 2L, 1L), .Label = c("donald", 
"jake", "joe"), class = "factor"), last_name = structure(c(1L, 
3L, 2L), .Label = c("asdf", "jong", "qwerty"), class = "factor"), 
    year = c(2018, 2017, 2018), age = c(12, 34, 5)), .Names = c("first_name", 
"last_name", "year", "age"), row.names = c(NA, -3L), class = "data.frame")