Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of letters to sequence of numbers R

Tags:

string

numbers

r

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
like image 507
Pexav01 Avatar asked Dec 30 '25 16:12

Pexav01


1 Answers

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"
like image 66
akrun Avatar answered Jan 01 '26 06:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!