I have a data frame that looks like:
df <- as.data.frame(c("AAA", "AAB", "AAC", "BBA"))
df
1 AAA
2 AAB
3 AAC
4 BBA
And I want to obtain something like:
1 111
2 112
3 113
4 221
In base R, we can use chartr
df[[1]] <- chartr("ABC", "123", df[[1]])
df[[1]]
#[1] "111" "112" "113" "221"
In case if the values that replaces have more than one character, then a general solution is str_replace_all - use a named key/value vector to match and replace
library(stringr)
str_replace_all(df[[1]], setNames(c("1", "2", "3"), c("A", "B", "C")))
[1] "111" "112" "113" "221"
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