[R] ASCII map?

Mark Myatt mark at myatt.demon.co.uk
Wed May 9 12:45:32 CEST 2001


Henrik Bengtsson <henrikb at braju.com> writes:

>Is there a way to convert between and integer and a character and vice
>versa? For instance
>
>   i <- 65;
>   ch <- intToChar(i);  # "A"
>   i <- charToInt(ch);  # 65
>

charToInt() can be done with charmatch():

        ch <- "a"
        i <- charmatch(ch, letters) + 96
        i
        
And I guess that it will work the other way round:

        i <- 99
        ch <- letters[i - 96]
        ch

the vector 'letters' is already defined in R but contains only lower
case characters ... it is simple to create an ASCIITable vector and use
that:

        ASCIITable <- c("A", "B", "C", "D", "E", "F", "G", "H",
                        "I", "J", "K", "L", "M", "N", "O", "P",
                        "Q", "R", "S", "T", "U", "V", "W", "X",
                        "Y", "Z", " ", " ", " ", " ", " ", " ",
                        "a", "b", "c", "d", "e", "f", "g", "h",
                        "i", "j", "k", "l", "m", "n", "o", "p",
                        "q", "r", "s", "t", "u", "v", "w", "x",
                        "y", "z")
        i <- 65
        ch <- ASCIITable[i - 64]
        ch
        i <- charmatch(ch, ASCIITable) + 64
        i
        
>or even better
>
>   i <- c(65, 66);
>   ch <- intToChar(i);  # c("A", "B")
>   i <- charToInt(ch);  # c(65, 66)

R functions handle the increase in complexity of passed objects
automatically:

        i <- c(65, 66)
        ch <- ASCIITable[i - 64]
        ch
        i <- charmatch(ch, ASCIITable) + 64
        i

Mind you, there might be a set of character function that I don't know
about.

I hope that helps.

Mark


--
Mark Myatt
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list