R:固定为T的精确完整字符串的gsub [英] R: gsub of exact full string with fixed = T

查看:139
本文介绍了R:固定为T的精确完整字符串的gsub的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试精确地输入gsub完整字符串-我知道我需要使用^$.问题是我在字符串中有特殊字符(可能是[.),因此我需要使用fixed=T.这将覆盖^$.任何解决方案表示赞赏. 需要将exact_orig中的第一,第二元素替换为exact_change中的第一,第二元素,但前提是必须从头到尾都匹配完整的字符串.

I am trying to gsub exact FULL string - I know I need to use ^ and $. The problem is that I have special characters in strings (could be [, or .) so I need to use fixed=T. This overrides the ^ and $. Any solution is appreciated. Need to replace 1st, 2nd element in exact_orig with 1st, 2nd element from exact_change but only if full string is matched from beginning to end.

exact_orig = c("oz","32 oz")
exact_change = c("20 oz","32 ct")

gsub_FixedTrue <- function(i) {
  for(k in seq_along(exact_orig)) i = gsub(exact_orig[k],exact_change[k],i,fixed=TRUE)
  return(i)
}

测试用例:

print(gsub_FixedTrue("32 oz")) #gives me "32 20 oz" - wrong! Must be "32 ct"
print(gsub_FixedTrue("oz oz")) # gives me "20 oz 20 oz" - wrong! Must remain as "oz oz"

我读了一个有点类似的线程,但是不能使它适用于完整字符串(

I read a somewhat similar thread, but could not make it work for full string (grep at the beginning of the string with fixed =T in R?)

推荐答案

如果您想完全匹配完整字符串,我不认为您真的想在这种情况下使用正则表达式.只是match()函数

If you want to exactly match full strings, i don't think you really want to use regular expressions in this case. How about just the match() function

fixedTrue<-function(x) {
    m <- match(x, exact_orig)
    x[!is.na(m)] <- exact_change[m[!is.na(m)]]
    x
}

fixedTrue(c("32 oz","oz oz"))
# [1] "32 ct" "oz oz"

这篇关于R:固定为T的精确完整字符串的gsub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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