0

I have two data frame:

df1<- data.frame(place=c("KARACA ADANA","ASIL BOLU","GAZIANTEP","YUKARI/MERSIN"))
df2<- data.frame(city=c("ADANA","BOLU","ANTEP","MERSIN"), neighbor=c("KARACA","ASIL","GAZI","YUKARI"))

I need to match columns df1$place and df2$neighbor. If df1$place contains the word in df2$neighbor, it should create a new column to df1$newcol by copying the corresponding value of df2$city of matches.

df1$newcol <- data.frame(place=c("KARACA ADANA","ASIL BOLU","GAZIANTEP","YUKARI/MERSIN") ,city=c("ADANA","BOLU","ANTEP","MERSIN"))
Ian Campbell
  • 21,281
  • 13
  • 26
  • 51
genco
  • 25
  • 6

2 Answers2

1

Here's an approach with sapply from base R:

If you want only whole words to match, you could use a regular expression. \\b looks for a word boundary.

ind <- unlist(sapply(df2$neighbor, function(x) grep(paste0("\\b",x,"\\b"),df1$place)))
ind2 <- rep(1:length(df2$neighbor),
            times = sapply(df2$neighbor, function(x) length(grep(paste0("\\b",x,"\\b"),df1$place))))
df1$newcol <- NA
df1$newcol[ind] <- as.character(df2$city[ind2])
df1
#          place newcol
#1  KARACA ADANA  ADANA
#2     ASIL BOLU   BOLU
#3     GAZIANTEP   <NA>
#4 YUKARI/MERSIN MERSIN
#5 YUKARI/MERSIN MERSIN
#6     GAZIANTEP   <NA>
#7     ASIL BOLU   BOLU
#8  KARACA ADANA  ADANA

Sample Data

df1<- data.frame(place=c(c("KARACA ADANA","ASIL BOLU","GAZIANTEP","YUKARI/MERSIN"),
                         rev(c("KARACA ADANA","ASIL BOLU","GAZIANTEP","YUKARI/MERSIN"))))
Ian Campbell
  • 21,281
  • 13
  • 26
  • 51
0

try to do it this way

library(tidyverse)
df1 %>% 
  rowwise() %>% 
  mutate(out = df2$city[str_which(place, df2$city)])
Yuriy Saraykin
  • 7,360
  • 1
  • 6
  • 12