'Sequence of letters to sequence of 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


Solution 1:[1]

Another option is to use LETTERS from base R and a named vector to convert the letters to their respective numbers.

libary(tidyverse) 

map_chr(strsplit(df$x, ""), ~ str_flatten(setNames(seq_along(LETTERS), LETTERS)[.]))
[1] "111" "112" "113" "221"

Solution 2:[2]

Another option is using gsubfn to replace the letters with their number:

library(gsubfn)
v <- setNames(seq_along(LETTERS), LETTERS)
transform(df, numbers = gsubfn("(.)", as.list(v), df[[1]]))

Output:

  c..AAA....AAB....AAC....BBA.. numbers
1                           AAA     111
2                           AAB     112
3                           AAC     113
4                           BBA     221

Solution 3:[3]

Here is another base R trick using utf8ToInt

> v <- c("AAA", "AAB", "AAC", "BBA")

> sapply(v, function(x) crossprod(utf8ToInt(x) - 64, 10^((nchar(x):1) - 1)))
AAA AAB AAC BBA 
111 112 113 221

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LMc
Solution 2
Solution 3 ThomasIsCoding