使用带有额外条件的 `match()` 匹配模式

Matching a pattern with `match()` with extra condition

扩展上一个问题 ()。 [非常感谢所有在那里提供帮助的人。特别感谢@MrFlick]

我需要将“32 oz”更改为“32 ct”,但前提是满足额外条件“3”,其他任何情况都不需要。

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”

这个有效:

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

已修改以检查 flag 和 orig 中的位置是否相同

稍微接近原作:

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