基于R中的最后三个字符合并数据

基于R中的最后三个字符合并数据,r,merge,R,Merge,我想把机场代码1和机场代码2合并成最后三个 机场代码的字母。如果最后3封来自机场的信\u代码。1 匹配机场代码。2打印机场代码。1 Airport_Code.1 Airport_Code.2 1 AJFK BWI 2 ABWI JSJ 3 BJSJ

我想把机场代码1和机场代码2合并成最后三个 机场代码的字母。如果最后3封来自机场的信\u代码。1 匹配机场代码。2打印机场代码。1

        Airport_Code.1       Airport_Code.2      
    1       AJFK                 BWI              
    2       ABWI                 JSJ              
    3       BJSJ                 JFk              
    4       ....                 ...             
    5       ....                 ...             
一些数据:

a = sample(LETTERS, 20)
b = sample(LETTERS, 20)
c = sample(LETTERS, 20)
d = sample(LETTERS, 20)

Airport_Code.2 = paste0(a,b,c)
Airport_Code.1 = paste0(d,a,b,c)

df = data.frame(Airport_Code.1, Airport_Code.2)

df$Airport_Code.1 = as.character(df$Airport_Code.1)
df$Airport_Code.2 = as.character(df$Airport_Code.2)
使用nchar查找机场代码.1中的字母数,使用子字符串隔离最后3个字母,如果匹配,使用ifelse返回机场代码.1,如果不匹配,则返回NA

n_air = nchar(df$Airport_Code.1)
Result_Airport = ifelse(substring(Airport_Code.1,  n_air-2, n_air) ==  Airport_Code.2, Airport_Code.1, NA)

purrr::map
解决方案

df$Result <- map_chr(1:nrow(df), ~ifelse(grepl(df[.x,2], df[.x,1]), as.character(df[.x,1]), NA))
你的数据

df <- read.table(text="Airport_Code.1       Airport_Code.2     Result_Airport 
   AJFK                 JFK              AJFK
  ABWI                 BWI              ABWI
  BJSJ                 JSJ              BJSJ", header=TRUE)
df
df <- read.table(text="Airport_Code.1       Airport_Code.2     Result_Airport 
   AJFK                 JFK              AJFK
  ABWI                 BWI              ABWI
  BJSJ                 JSJ              BJSJ", header=TRUE)