Reputation: 321
I have two vectors p1,p2 they report the same information except p2 is more precise. So I want to pick compare the 2 and pick the value from p2 except if the difference between the 2 vectors is > k. In that case I want the value from p1 to be picked in the final product "pd".
k <- 5
p1 <- c(21,43,62,88,119,156,264)
p2 <- c(19,42,62,84,104,156,262)
pd should look like:
pd <- c(19,42,62,84,119,156,262)
I have seen code that specified the selection condition inside the square brackets, but can't figure out how to duplicate it. Something similar to pd <- p2[p1, p1-p2 >5], but not exactly because this obviously doesn't evaluate. p2[p1-p2<5] works to select the positive cases but the 5th case where the condition evaluate to FALSE is skipped.
Upvotes: 2
Views: 749
Reputation: 887088
May be
ifelse(abs(p2-p1) <=k, p2, p1)
#[1] 19 42 62 84 119 156 262
Or without using ifelse
indx <- abs(p1-p2) >k
pd <- p2
pd[indx] <- p1[indx]
pd
#[1] 19 42 62 84 119 156 262
Upvotes: 1