r - 按参数模式和左连接进行匹配

标签 r regex merge left-join

我正在尝试将城市/县名称(幸运的是提供了州名称信息)与其相应的州名称相匹配,然后使用 left_join() 将其前三个电话数字附加为另一列。我最初的想法是复制城市/县名称列,然后使用 sapply()grep() 将其替换为州名称,然后使用 left_join() 将其与电话数字列合并,但我的代码似乎不起作用。

library(dplyr)

location <- data.frame(location = c('Asortia, New York', 'Buffalo, New York', 'New York, New York',  'Alexandra, Virginia', 'Fairfax, Virginia', 'Baltimore, Maryland', 'Springfield, Maryland'), number = c(100, 200, 300, 400, 500, 600, 700))

state <- data.frame(state = c('New York', 'Virginia', 'Maryland'))

sapply(as.character(state$state), function(i) grep(i, location$location))

### doesn't work! ###
### my desired output would be ###

  location number
1 New York    100
2 New York    200
3 New York    300
4 Virginia    400
5 Virginia    500
6 Maryland    600
7 Maryland    700
这样我就可以使用 left_join 将上面生成的输出与他们的三位数电话号码合并。例如,

df <- location
names(df)[1] <- 'state'
digit <- data.frame(state = c('New York', 'Virginia', 'Maryland'), digit = c(212, 703, 410))
   
new_df <- left_join(df, digit, by = 'state')

### the desired output ###

  location number digit
1 New York    100   212
2 New York    200   212
3 New York    300   212
4 Virginia    400   703
5 Virginia    500   703
6 Maryland    600   410
7 Maryland    700   410

我已经引用了thisthis线程,但没有完全掌握线索。 希望有人能帮助我解决这个问题。

## 更新

我发现在for循环中使用grepl也可以,但是如果你有大量数据(我正在处理的数据),处理可能会很慢有 200 万个观测值)。

for (i in state$state) { 
location$location[grepl(i, location$location)] <- i
}

最佳答案

也许我们可以通过在“state”中粘贴(str_c)pattern向量来使用str_remove “state”数据集中的列作为正则表达式查找,以匹配向量之前的任何内容(要删除)

library(stringr)
library(dplyr)
location %>%
    mutate(location = str_remove(location, str_c(".*(?=(",
            str_c(state$state, collapse  = "|"), "))")))
#  location number
#1 New York    100
#2 New York    200
#3 New York    300
#4 Virginia    400
#5 Virginia    500
#6 Maryland    600
#7 Maryland    700

或者另一种选择是将分隔分成两列并删除第一个

library(tidyr)
location %>%
   separate(location, into = c('unwanted', 'location'), sep=",\\s*") %>% 
   select(-unwanted)

或者,如果我们有特定模式,请通过从开头匹配一个或多个不是 , 的字符 (^) 来删除前缀部分,后跟 , 和零个或多个空格 (\\s*) 作为 str_remove

中的模式
location %>% 
    mutate(location = str_remove(location, '^[^,]+,\\s*'))

关于r - 按参数模式和左连接进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59057525/

相关文章:

r - 如何从日期中提取季度?

c++ - 与boost正则表达式库的递归匹配

python - 如何从 Pandas 列中提取特定信息?

list - 在 Common Lisp 中合并两个列表

merge - Mercurial:执行 merge 时为 "no match found",如果我尝试剥离则为 "no node!"

R knitr 来自数据帧的有序列表

r - 如何在 R 基础包中向 ordiellipse 添加颜色和图例?

r - 无变量数据时添加NULL

Java 正则表达式 : Matching the beginning of a line

spring - 将分离的实体合并到 JPA 中的实体管理器的最佳方法是什么