Home > Mobile >  Sequence of letters to sequence of numbers R
Sequence of letters to sequence of numbers R

Time:05-21

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

CodePudding user response:

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"

CodePudding user response:

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"
  • Related