将字符串转换为一位数字并求和 [英] Convert string to single digits and sum

查看:150
本文介绍了将字符串转换为一位数字并求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了好几个小时来找到解决方案,但我失败了。

I've tried for hours to find a solution to what I thought was an easy task but I failed.

我有一个字符串,包含3个不同的字符('I','R'&'O'),长度从1到6。

Eg

I have a string consisting of 3 different characters ('I','R' & 'O') with length from 1 to 6.
E.g

IRRROO
RRORRR
IIR
RIRRO

每个字符代表一个数字 I = 1,R = 2,O = 3

我需要将此字符串转换为一个数字,再乘以位置并求和。例如

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

感谢

推荐答案

因子具有数值等效项。您可以在此示例中很好地利用它:

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

这篇关于将字符串转换为一位数字并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆