R, Statistics

Generating character from number

The sequence operator, “:”, is useful.  A 1:26 generates an integer series from 1 to 26.  However, an ‘A’:’Z’ causes error.  I need a sequence of characters sometimes.

The 1st example is using raw byte array.  This is the most simple way and it works for both ascii and utf-8.

> rawToChar(as.raw(65:90), multiple=T)
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q"
[18] "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

> rawToChar(as.raw(as.hexmode(c('e2','84','9c'))))
[1] "ℜ"

The 2nd example is a trick using the regular expression.

> AtoZ <- c(chartr('[0-9]', '[A-J]', 0:9), chartr('[0-9]', '[K-T]', 0:9), chartr('[0-5]', '[U-Z]', 0:5))
> AtoZ
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R"
[19] "S" "T" "U" "V" "W" "X" "Y" "Z"

The 3rd example evaluates an escaped character.

> eval(parse(text=paste("'\\x", "67", "'", sep="")))
[1] "g"

> eval(parse(text=paste("'\\x",as.hexmode(97),"'",sep="")))
[1] "a"

> sapply(97:122,function(i) eval(parse(text=paste("'\\x",as.hexmode(i),"'",sep=""))))
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r"
[19] "s" "t" "u" "v" "w" "x" "y" "z"

When a unicode character is needed, the following works.

> eval(parse(text="'\\u00AE'"))
[1] "®"

Mind that this is a registered sign, not an R logo.


One comment on “Generating character from number

  1. tomizono
    April 11, 2013

    Just for ‘A’ to ‘Z’, letters and LETTERS work. (Thanks, Scott. I didn’t know these predefined vecrtors.) But the above is a generalized way that can handle non-alphabet characters.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


This entry was posted on April 10, 2013 by and tagged , , , , , , , , , .
The stupidest thing...

Statistics, genetics, programming, academics


R, Statistics

%d bloggers like this: