Convert strings to single digits and sum

I tried for several hours to find a solution to what, in my opinion, was an easy task, but I could not.

I have a string consisting of 3 different characters ('I','R' & 'O') from 1 to 6 in length.
for example

 IRRROO RRORRR IIR RIRRO 

Each character represents a number I=1,R=2,O=3
I need to convert this string to one number, multiply by position and summarize the result. for example

 IRRROO ---> (1*1)+(2*2)+(2*3)+(2*4)+(3*5)+(3*6) =52 IIR ---> (1*1)+(1*2)+(2*3) =9 

Thanks in advance for your help.

+8
text r recursion sum character
source share
2 answers
Factors

have numerical equivalents. You can use this for this example:

 # original x1 <- "IRRROO" # 1 2 3 levs <- c("I", "R", "O") # split the string and convert to factors, then to numeric x1f <- as.numeric(factor(strsplit(x1, "")[[1]], levels=levs)) # tally it up sum(x1f * seq_along(x1f)) 

Or as a nice one-line function:

 sumValue <- function(x, levs=c("I", "R", "O")) sum(seq.int(nchar(x)) * as.numeric(factor(strsplit(x, "")[[1]], levels=levs))) sumValue("IRRROO") # [1] 52 sumValue("IIR") # [1] 9 
+11
source share

An alternative version using a named vector as input, allowing you to assign an arbitrary numeric value to each letter:

 vals <- c(I=1,R=2,O=3) test <- c("IRRROO","RRORRR","IIR","RIRRO") sumValue <- function(dat,vals) { tmp <- strsplit(dat,"") vapply(tmp,function(x) sum(seq_along(x) * vals[x]),numeric(1)) } sumValue(test,vals) [1] 52 45 9 33 
+7
source share

All Articles