I want to substitute all A
's for B
's and B
's for A
's in a string in R.
My input is
x = "ABCDBBABDC"
and my output should be,
y = "BACDAABADC"
How could I do this in one line?
I tried sub
but I cannot do multiple substitutions.
Use replace() to replace substrings. Specify the old string old for the first argument and the new string new for the second argument.
The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.
You are looking for chartr
:
x = "ABCDBBABDC"
chartr("AB", "BA", x)
# [1] "BACDAABADC"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With