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, ie
paste0("x == ", '36', "| x == ", "944, "| x == ")
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'"
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.
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.