Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute A for B and B for A in a string

Tags:

regex

r

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.

like image 317
Dnaiel Avatar asked Oct 02 '13 16:10

Dnaiel


People also ask

How do you replace two words in a string in Python?

Use replace() to replace substrings. Specify the old string old for the first argument and the new string new for the second argument.

How do you replace letters in a string in Python?

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.


1 Answers

You are looking for chartr:

x = "ABCDBBABDC"
chartr("AB", "BA", x)
# [1] "BACDAABADC"
like image 174
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 31 '22 19:10

A5C1D2H2I1M1N2O1R2T1