Home > Net >  Convert character string to number in R
Convert character string to number in R

Time:09-29

I am trying to convert a character string to a number in R. Example:

a=1; b=2

If my input is "abba", I want my output to be a b b a = 1 2 2 1 = 6. Here's my attempt so far:

str= "abba"
paste(unlist(strsplit(unlist(str_extract_all(str, "[aA-zZ] ")), split = "")),collapse=" ")
[1] "a b b a"

I don't know how to convert this to numeric since as.numeric() returns NA. Any help is appreciated!

CodePudding user response:

You could use a data.frame to translate your letters to numbers, and match after using strsplit:

translation <- data.frame(letter = letters, 
                          number = 1:26)
str <- "abba"
sum(match(strsplit(str, "")[[1]], translation$letter))
#> [1] 6

CodePudding user response:

Another option setting factor levels for the letters like this:

str= "abba"
sum(as.numeric(factor(unlist(strsplit(str, "")), levels = letters)))
#> [1] 6

Created on 2022-09-28 with reprex v2.0.2

CodePudding user response:

An option with chartr

eval(parse(text = chartr('ab', '12', gsub("(?<=\\w)(?=\\w)", " ",
    str, perl = TRUE))))
[1] 6
  •  Tags:  
  • r
  • Related