Re: [R] Calculating sum of letter values

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Mon, 24 Nov 2008 09:08:48 -0600

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



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:11:07 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