从R中的另一个数据帧中查找所有字符串匹配项

时间:2017-10-05 18:52:39

标签: r string design-patterns extract grepl

我在R中比较新。

我的数据框locs有1个变量V1,如下所示:

V1
edmonton general hospital
cardiovascular institute, hospital san carlos, madrid spain
hospital of santa maria, lisbon, portugal

另一个数据框cities有两个看起来像这样的变量:

city              country
edmonton          canada
san carlos        spain
los angeles       united states
santa maria       united states
tokyo             japan
madrid            spain
santa maria       portugal
lisbon            portugal

我想在locs中创建两个与V1city的任何字符串匹配相关的新变量,以便locs看起来像这样:

V1                                            city                  country                      
edmonton general hospital                     edmonton              canada
hospital san carlos, madrid spain             san carlos, madrid    spain
hospital of santa maria, lisbon, portugal     santa maria, lisbon   portugal, united states

需要注意的一些事项:V1可能有多个国家/地区名称。此外,如果有一个重复的国家(例如,圣卡洛斯和马德里都在西班牙),那么我只想要一个国家的一个实例。

请告知。

感谢。

1 个答案:

答案 0 :(得分:1)

使用tidyversestringr的解决方案。 locs2是最终输出。

library(tidyverse)
library(stringr)

locs2 <- locs %>%
  rowwise() %>%
  mutate(city = list(str_match(V1, cities$city))) %>%
  unnest() %>%
  drop_na(city) %>%
  left_join(cities, by = "city") %>%
  group_by(V1) %>%
  summarise_all(funs(toString(sort(unique(.)))))

<强>结果

locs2 %>% as.data.frame()
                                                           V1                city                 country
1 cardiovascular institute, hospital san carlos, madrid spain  madrid, san carlos                   spain
2                                   edmonton general hospital            edmonton                  canada
3                   hospital of santa maria, lisbon, portugal lisbon, santa maria portugal, united states

数据

library(tidyverse)

locs <- data_frame(V1 = c("edmonton general hospital",
                   "cardiovascular institute, hospital san carlos, madrid spain",
                   "hospital of santa maria, lisbon, portugal"))

cities <- read.table(text = "city              country
edmonton          canada
'san carlos'        spain
'los angeles'       'united states'
'santa maria'       'united states'
tokyo             japan
madrid            spain
'santa maria'       portugal
lisbon            portugal",
                     header = TRUE, stringsAsFactors = FALSE)