Manofbear
Manofbear

Reputation: 3

R function to select value from two vectors, based on condition

I have three vectors, v_1,v_2,b. b consists of booleans. I would like to construct a new vector v that takes as its ith coordinate the value v_1[[i]] if b[[i]]==TRUE, and v_2[[i]] otherwise. Is there a vectorized function that does this?

Sorry if the question is too basic.

Thank you in advance!

Upvotes: 0

Views: 30

Answers (1)

Peter
Peter

Reputation: 12699

set.seed(123)
v_1 <- letters[1:5]
v_2 <-  1:5
b <- sample(c(TRUE, FALSE), 5, replace = TRUE)

v <- ifelse(b, v_1, v_2)
v
#> [1] "a" "b" "c" "4" "e"

Created on 2021-09-20 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions