[R] Calculating sum of letter values

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 24 16:17:12 CET 2008


Here are a couple of solutions.

The first matches each
character against LETTERS returning the position number
in LETTERS of the match.  strsplit returns a list of which
we want the first element and then we sum that.

The second applies function(x) match(x, LETTERS),
which is specified in formula notation, to each letter
and simplifies the result using sum.

sum(match(strsplit(s, "")[[1]], LETTERS))

library(gsubfn)
strapply(s, ".", ~ match(x, LETTERS), simplify = sum)

On Mon, Nov 24, 2008 at 9:57 AM,  <Rory.WINSTON at rbs.com> wrote:
> Hi all
>
> If I have a string, say "ABCDA", and I want to convert this to the sum of the letter values, e.g.
>
> A -> 1
> B -> 2
>
> etc, so "ABCDA" = 1+2+3+4+1 = 11
>
> Is there an elegant way to do this? Trying something like
>
> which(LETTERS %in% unlist(strsplit("ABCDA", "")))
> is not  quite correct, as it does not count repeated characters. I guess what I need is some kind of lookup table?
>
> Cheers
> Rory
>
> Rory Winston
> RBS Global Banking & Markets
> 280 Bishopsgate, London, EC2M 4RB
> Office: +44 20 7085 4476
>
>
>
> ***********************************************************************************
> The Royal Bank of Scotland plc. Registered in Scotland No 90312. Registered Office: 36 St Andrew Square, Edinburgh EH2 2YB.
> Authorised and regulated by the Financial Services Authority
>
> This e-mail message is confidential and for use by the=2...{{dropped:25}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list