What is the best way of using a character vector, such as:
vector <- c("36","944","38","994")
To generate a string like this:
new_string <- "x == '36'| x == '944'| x == '38'| x == '994'"
I tried using paste0
but I am searching for a more efficient way to do this, i.e.
paste0("x == ", '36', "| x == ", "944, "| x == ")
CodePudding user response:
We may use %in%
here instead of ==
(assuming that the end goal is to subset a vector x
based on the values in vector
x %in% vector
If we want to use ==
, this can be done with Reduce
Reduce(`|`, lapply(vector, function(u) x == u))
If the intention is to create a string, use collapse
in paste
paste0('x==', "'", vector, "'", collapse = "|")
[1] "x=='36'|x=='944'|x=='38'|x=='994'"
CodePudding user response:
paste0 is actually efficient, as R is a vectorized language. Try this:
vector <- c("36","944","38","994")
paste0("x == '", vector, "'",collapse = "|")
Hope it is helpful.