如果列表中的单词与字符串中的单词匹配,是否有R函数返回值

时间:2019-05-07 09:27:36

标签: r

是否存在R函数来检查列表中的单词是否存在于字符串中,如果是,则返回另一个值?

Address
10 Sydney, South East
11 Mumbai, North West
12 London, Central Town

City  Country
Mumbai India
Sydney Australia
London Britain

输出:

Address                   Country
10 Sydney, South East     Australia
11 Mumbai, North West     India
12 London, Central Town   Britain

示例代码-

influencer %>%
    mutate(AC.Name = AC_Village$AC.Name[match(AC_Village$Town, 
           str_extract(Complete.Address,paste(AC_Village$Town, collapse="|")))])

1 个答案:

答案 0 :(得分:0)

一种选择是从第二个数据集的“城市”列中提取“地址”列的“城市”,执行match并获得相应的“国家”

library(tidyverse)
df1 %>% 
   mutate(Country = df2$Country[match(df2$City, str_extract(Address, 
          paste(df2$City, collapse="|")))])
#                   Address  Country
#1   10 Sydney, South East Australia
#2   11 Mumbai, North West     India
#3 12 London, Central Town   Britain

数据

df1 <- structure(list(Address = c("10 Sydney, South East", "11 Mumbai, North West", 
"12 London, Central Town")), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(City = c("Mumbai", "Sydney", "London"), Country = c("India", 
"Australia", "Britain")), class = "data.frame", row.names = c(NA, 
-3L))