How can I remove an expression that is stored in a variable from a string in base R?

How can I remove an expression that is stored in a variable from a string in base R?

Problem Description:

For example, I have variable x = "a1" while I also have another variable y = "5a1".
How could I make y = "5" while still using the x variable?

I tried using gsub() with but it only seems to work if it is inside double quotes. Is there a variable equivalent for ?

Solution – 1

You can do:

x <- "a1"
y <- "5a1"
gsub(pattern = paste0(x, "$"), replacement = "", x = y)

$ is used to match end of string

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject