匹配模式与`match()`与额外条件

时间:2015-06-18 15:44:16

标签: r match conditional-statements

扩展上一个问题(R: gsub of exact full string with fixed = T)。 [非常感谢帮助那里的每个人。特别感谢@MrFlick]

我需要改变" 32盎司"至" 32 ct"但只有在额外条件下才会出现#34; 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"

我不知道第一次&#34; 32盎司&#34;更改为&#34; 32 ct&#34;如果测试用例中的标志是&#34; 1&#34;不是&#34; 3&#34;

1 个答案:

答案 0 :(得分:2)

这有效:

fixedTrue <- function(x, y) {
   toChange <- which(match(x, exact_orig) == match(y, exact_flag))
   x[toChange] <- exact_change[match(x[toChange], exact_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)]]
}