R:将"+"替换为带gsub的字符 [英] R: Replace "+" character with gsub

查看:121
本文介绍了R:将"+"替换为带gsub的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题似乎很琐碎,但我无法弄清楚为什么它不起作用.我只想用单个值(不包括"+"运算符)替换涉及"+"运算符的字符变量.由于某些原因,gsub()和sub()函数替换了数字值,但保留了运算符.关于如何可以克服的任何提示? 非常感谢!

the question seems totally trivial but I cannot figure out why it isn't working. I simply want to replace a character variable involving a "+" operator with a single value excluding the "+" operator. For some reason gsub() and sub() function replace the number value but keep the operator. Any hint on how this can be overcome? Many thanks!

data <- c(1,2,3,4,"5+")
gsub(pattern="5+",replacement="5",x=data)
#[1] "1"  "2"  "3"  "4"  "5+"

gsub(pattern="5+",replacement="",x=data)
#[1] "1"  "2"  "3"  "4"  "+"

R 3.0.2

推荐答案

+是一个元字符,要与之匹配时需要转义:

+ is a metacharacter, and needs to be escaped when you want to match it:

gsub(pattern="5\\+",replacement="5",x=data)
#[1] "1" "2" "3" "4" "5"

或更一般而言,如果要删除+:

Or more generally, if you want to remove the +:

gsub(pattern="\\+",replacement="",x=data)

如果不转义,+表示前一项将被匹配一次或多次",因此在您的第二个示例中,"5+""5"元素由模式匹配,并由""代替,留下"+".

If unescaped, + means "The preceding item will be matched one or more times", so in your second example, the "5" element of "5+" is matched by the pattern, and replaced by "", leaving you with "+".

这篇关于R:将"+"替换为带gsub的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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