我正在尝试将城市/县名称(幸运的是提供了州名称信息)与其相应的州名称相匹配,然后使用 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
我已经引用了this和 this线程,但没有完全掌握线索。 希望有人能帮助我解决这个问题。
## 更新我发现在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/