r - conditional subseting with square brackets or inside square brackets -



r - conditional subseting with square brackets or inside square brackets -

i have 2 vectors p1,p2 study same info except p2 more precise. want pick compare 2 , pick value p2 except if difference between 2 vectors > k. in case want value p1 picked in 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 like:

pd <- c(19,42,62,84,119,156,262)

i have seen code specified selection status within square brackets, can't figure out how duplicate it. similar pd <- p2[p1, p1-p2 >5], not because doesn't evaluate. p2[p1-p2<5] works select positive cases 5th case status evaluate false skipped.

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

r

Comments