Re: [R] Calculating sum of letter values

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Mon, 24 Nov 2008 10:17:12 -0500

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.
>



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. Received on Mon 24 Nov 2008 - 15:23:36 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 24 Nov 2008 - 15:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive