1

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  == ")  

2 Answers 2

1

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'"
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks so much akrun! Would you happen to know why I am getting a '\' when using collapse? Ie. 'x == \'1\'|x == \'2\''
@KatherineDrummond Maybe you added " instead of '
Apologies, still struggling. This is what I am running - looks identical to the suggestion. vector <- c("36","944","38","994") paste0('x==', "'", vector, "'", collapse = "|")
@KatherineDrummond with that code, I am not getting the \ i.e. paste0('x==', "'", vector, "'", collapse = "|")# [1] "x=='36'|x=='944'|x=='38'|x=='994'"
How bizzare. Thanks for your help akrun
|
1

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.

2 Comments

Please run these code above and see the outcome. The main difference is that the code above recycles any lengths of vector values; whereas the example code in the question manually wrote all of them out.
I see! Sorry I thought you are the author of the question - didn't realize you have answered this question already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.