提问人:Rokas 提问时间:9/12/2023 更新时间:9/19/2023 访问量:38
如何使用 r 在邮政编码中找到两个三
How to find two threes in zip code using r
问:
我需要有关此任务的帮助: 打印地址 .zip 代码中包含两个 3 的位置的数据。 我试过了:
filtered_data <- df %>%
filter(grepl("\\d{3}.*\\d{3}", address.zip))
print(filtered_data)
它没有给出任何输出,但我知道数据文件中有两个 3 的邮政编码
答:
0赞
Richard Careaga
9/19/2023
#1
library(stringr)
d <- data.frame(
zipcode = c("00001", "10003", "20003", "30003"),
addr = c("123 Main", "456 Maple", "789 Mulberry", "12302 Arrow")
)
d[which(str_count(d$zipcode,"3") == 2),"zipcode"]
[1] "30003"
创建于 2023-09-19 使用 reprex v2.0.2
0赞
Chris Ruehlemann
9/19/2023
#2
根据您需要过滤的内容,这里有两种解决方案:
library(dplyr)
library(stringr)
您想要过滤两个 s 直接相邻的邮政编码:3
df %>%
filter(str_detect(zipcode, "33"))
zipcode
1 83310
您想要过滤邮政编码,其中两个 s 按任意顺序出现:3
df %>%
filter(str_detect(zipcode, "3.*3"))
zipcode
1 83310
2 35389
3 73123
在这里,模式匹配 a 后跟任何字符 () 出现 0 次或多次 () 后跟3.*3
3
.
*
3
玩具数据:
df <- data.frame(
zipcode = c("90001", "83310", "35389", "73123")
)
下一个:查找组合的问题
评论
\\d{3}
表示出现三次的数字。它不是指字面数字“3”。尝试 如果包含一个简单的可重现示例,其中包含可用于测试和验证可能的解决方案的示例输入和所需输出,则更容易为您提供帮助。3.*3