[R] Calculating sum of letter values

Marc Schwartz marc_schwartz at comcast.net
Mon Nov 24 16:08:48 CET 2008


on 11/24/2008 08: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


> sum(as.numeric(factor(unlist(strsplit("ABCDA", "")))))
[1] 11


Convert the letters to factors, after splitting the vector, which then
enables the use of the underlying numeric codes:

> as.numeric(factor(unlist(strsplit("ABCDA", ""))))
[1] 1 2 3 4 1

HTH,

Marc Schwartz



More information about the R-help mailing list