[R] Calculating sum of letter values

Berwin A Turlach berwin at maths.uwa.edu.au
Mon Nov 24 16:28:31 CET 2008


G'day Rory,

On Mon, 24 Nov 2008 14:57:57 +0000
<Rory.WINSTON at rbs.com> wrote:

> 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? [...]

R> sum(as.numeric(factor(unlist(strsplit("ABCDA","")), levels=LETTERS)))
[1] 11
R> sum(as.numeric(factor(unlist(strsplit("ABCEA","")), levels=LETTERS)))
[1] 12

HTH.

Best wishes,

	Berwin

=========================== Full address =============================
Berwin A Turlach                            Tel.: +65 6515 4416 (secr)
Dept of Statistics and Applied Probability        +65 6515 6650 (self)
Faculty of Science                          FAX : +65 6872 3919       
National University of Singapore
6 Science Drive 2, Blk S16, Level 7          e-mail: statba at nus.edu.sg
Singapore 117546                    http://www.stat.nus.edu.sg/~statba



More information about the R-help mailing list