gpt4 book ai didi

regex - 在 R 中,使用正则表达式匹配多个模式并将新列添加到列表

转载 作者:行者123 更新时间:2023-12-01 02:11:18 25 4
gpt4 key购买 nike

我找到了许多关于如何使用一个模式和一个替换来匹配和更新整个列表的示例,但我现在正在寻找的是一种在单个语句或循环中对多个模式和多个替换执行此操作的方法。

例子:

> print(recs)
phonenumber amount
1 5345091 200
2 5386052 200
3 5413949 600
4 7420155 700
5 7992284 600

我想插入一个名为“service_provider”的新列,其中/^5/作为 Company1,/^7/作为 Company2。

我可以用以下两行 R 来做到这一点:
recs$service_provider[grepl("^5", recs$phonenumber)]<-"Company1"
recs$service_provider[grepl("^7", recs$phonenumber)]<-"Company2"

然后我得到:
  phonenumber amount service_provider
1 5345091 200 Company1
2 5386052 200 Company1
3 5413949 600 Company1
4 7420155 700 Company2
5 7992284 600 Company2

我想提供一个列表,而不是一组离散的 grepl,这样可以更容易地将国家特定信息保存在一个地方,并将所有编程逻辑保存在另一个地方。
thisPhoneCompanies<-list(c('^5','Company1'),c('^7','Company2'))

在其他语言中,我会在电话公司列表中使用 for 循环
For every row in thisPhoneCompanies
Add service provider to matched entries in recs (such as the grepl statement)
end loop

但我知道这不是在 R 中做到的方式。

最佳答案

使用 stringi :

library(stringi)
recs$service_provider <- stri_replace_all_regex(str = recs$phonenumber,
pattern = c('^5.*','^7.*'),
replacement = c('Company1', 'Company2'),
vectorize_all = FALSE)

recs
# phonenumber amount service_provider
# 1 5345091 200 Company1
# 2 5386052 200 Company1
# 3 5413949 600 Company1
# 4 7420155 700 Company2
# 5 7992284 600 Company2

关于regex - 在 R 中,使用正则表达式匹配多个模式并将新列添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29070431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com