在有额外条件的情况下将模式与match()匹配 [英] Matching a pattern with `match()` with extra condition

查看:68
本文介绍了在有额外条件的情况下将模式与match()匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

扩展上一个问题( R:精确的gsub固定= T 的完整字符串). [非常感谢在此提供帮助的每个人.特别感谢@MrFlick]

Expanding on a previous question (R: gsub of exact full string with fixed = T). [With huge thanks to everyone who helped there. Special thanks to @MrFlick]

我需要将"32盎司"更改为"32克拉",但前提是要满足附加条件"3",而在其他情况下则不需要.

I need to change "32 oz" to "32 ct" but only if extra condition "3" is met, not in any other case.

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

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

print(fixedTrue(c("32 oz","oz oz","32 oz", "oz", "oz"),c("1","1","3","1","2")))

结果:

[1] "20 oz" "oz oz" "32 ct" NA      NA  

所需的输出:

[1] "32 oz" "oz oz" "32 ct" "20 oz" "oz"

尝试了以下操作

  x[!is.na(m&n)]<- exact_change[m[!is.na(m&n)]]

  print(fixedTrue(c("32 oz","oz oz","32 oz", "oz", "oz"),c("1","1","3","1","3")))

知道:

[1] "32 ct" "oz oz" "32 ct" "20 oz" "20 oz"

如果测试用例中的标记是"1"而不是"3",我看不到"32 oz"如何首先变为"32 ct"

I don't see how first "32 oz" changes to "32 ct" if the flag in test case is "1" not "3"

推荐答案

这有效:

fixedTrue <- function(x, y) {
   toChange <- which(match(x, exact_orig) == match(y, exact_flag))
   x[toChange] <- exact_change[match(x[toChange], exact_orig)]
}

修订为检查标志和原始位置中的位置

Amended to check positions in flag and orig the same

稍微接近原图:

fixedTrue <- function(x, y) {
  m <- match(x, exact_orig); n <- match(y, exact_flag)
  x[which(m == n)] <- exact_change[m[which(m == n)]]
}

这篇关于在有额外条件的情况下将模式与match()匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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