r - Convert string to single digits and sum -
i've tried hours find solution thought easy task failed.
i have string consisting of 3 different characters ('i','r' & 'o')
length 1 6.
e.g
irrroo rrorrr iir rirro
each character represents number i=1,r=2,o=3
need convert string single number, multiply position , sum 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 help.
factors have numeric equivalents. can leverage nicely example:
# original x1 <- "irrroo" # 1 2 3 levs <- c("i", "r", "o") # split string , convert factors, numeric x1f <- as.numeric(factor(strsplit(x1, "")[[1]], levels=levs)) # tally sum(x1f * seq_along(x1f))
or 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
Comments
Post a Comment