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]
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")))
Result:
[1] "20 oz" "oz oz" "32 ct" NA NA
Desired output:
[1] "32 oz" "oz oz" "32 ct" "20 oz" "oz"
Edit: tried the following
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")))
Got:
[1] "32 ct" "oz oz" "32 ct" "20 oz" "20 oz"
I don't see how first "32 oz" changes to "32 ct" if the flag in test case is "1" not "3"
This works:
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
Slightly closer to original:
fixedTrue <- function(x, y) {
m <- match(x, exact_orig); n <- match(y, exact_flag)
x[which(m == n)] <- exact_change[m[which(m == n)]]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.