R中的模式匹配和替换 [英] Pattern matching and replacement in R

查看:94
本文介绍了R中的模式匹配和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正则表达式一点都不熟悉,并且想在R中进行模式匹配和替换.

I am not familiar at all with regular expressions, and would like to do pattern matching and replacement in R.

我想用向量vec = c(1,2)的每个值替换向量original = c("#1", "#2", "#10", "#11")中的模式#1#2.

I would like to replace the pattern #1, #2 in the vector: original = c("#1", "#2", "#10", "#11") with each value of the vector vec = c(1,2).

我正在寻找的结果是以下向量:c("1", "2", "#10", "#11") 我不确定该怎么做.我尝试这样做:

The result I am looking for is the following vector: c("1", "2", "#10", "#11") I am not sure how to do that. I tried doing:

for(i in 1:2) {
    pattern = paste("#", i, sep = "")
    original = gsub(pattern, vec[i], original, fixed = TRUE)
}

但是我得到了:

#> original
#[1] "1"  "2"  "10" "11"

代替:"1" "2" "#10" "#11"

我将不胜感激!谢谢!

推荐答案

使用gsubfn的另一个选项:

library(gsubfn)
gsubfn("^#([1-2])$",  I, original)   ## Function substituting
[1] "1"   "2"   "#10" "#11"

或者,如果要使用vec值显式使用vector的值,则:

Or if you want to explicitly use the values of your vector , using vec values:

gsubfn("^#[1-2]$",  as.list(setNames(vec,c("#1", "#2"))), original) 

或等效于函数符号的公式符号:

Or formula notation equivalent to function notation:

gsubfn("^#([1-2])$",  ~ x, original)   ## formula substituting

这篇关于R中的模式匹配和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆