Home > OS >  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?

Time:12-06

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 \ \ ?

CodePudding user response:

You can do:

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

$ is used to match end of string

  • Related