[R] letters to numbers conversion
    Prof Brian Ripley 
    ripley at stats.ox.ac.uk
       
    Fri May  2 08:50:04 CEST 2003
    
    
  
On Thu, 1 May 2003, Tony Plate wrote:
> If you're looking for something that works with matrices or arrays you 
> could use the following.  Note that you would want to substitute LETTERS 
> for letters if your original data was in uppercase.  The stuff with 
> dimnames isn't necessary for this example, but it don't hurt and it will 
> preserve dimnames when the original data has them.
> 
>  > x <- matrix(letters[1:9],ncol=3)
>  > x
>       [,1] [,2] [,3]
> [1,] "a"  "d"  "g"
> [2,] "b"  "e"  "h"
> [3,] "c"  "f"  "i"
>  > match(x, letters)
> [1] 1 2 3 4 5 6 7 8 9
>  > array(match(x, letters), dim=dim(x), dimnames=dimnames(x))
>       [,1] [,2] [,3]
> [1,]    1    4    7
> [2,]    2    5    8
> [3,]    3    6    9
A useful trick here is to assign to foo[] as in
> y <- x; mode(y) <- "numeric"; y[] <- match(x, letters)
> y
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
That carries over all relevant attributes, so works for vectors, matrices, 
arrays ....  (Often you don't need to change the mode.)
-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595
    
    
More information about the R-help
mailing list