I've tried for hours to find a solution to what I thought was an easy task but I failed.
I have a string consisting of 3 different characters ('I','R' & 'O')
with length from 1 to 6.
E.g
IRRROO
RRORRR
IIR
RIRRO
Each character represents a number I=1,R=2,O=3
I need to convert this string to a single number, multiply with position and sum the result. E.g
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.
factors have numeric equivalents. You can leverage that nicely 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, single-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
Alternative version using a named vector as input, allowing arbitrary numeric value assignment 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