converting ascii number to strings in R
Asked Answered
J

3

10

To convert strings to ascii code in R, I typically use:

> strtoi(charToRaw("abcd"),16L)
[1] 97 98 99 100

Is there a function to do the inverse, i.e.

>myDesiredFunc(c(97 98 99 100)) 
[1] "abcd"

Thanks.

Jeopardize answered 17/4, 2014 at 2:0 Comment(0)
J
13

I just noticed that R has a intToUtf8 and utf8ToInt functions that does the same thing.

> test<-utf8ToInt("Apples")
> test
[1]  65 112 112 108 101 115
> intToUtf8(test)
[1] "Apples"
Jeopardize answered 18/4, 2014 at 23:20 Comment(0)
J
9

Also:

 rawToChar(as.raw(c(97,98,99,100)))

Type ?charToRaw at the command prompt for more info.

Juliannjulianna answered 17/4, 2014 at 2:11 Comment(4)
The obvious solution I suppose. :-PBlackpoll
Hm, how on earth I did not answer that?Sourwood
Probably trying to be the first to answer - it's the curse of stackoverflow. Answer too slowly and someone gets in first with almost the exact same response.Juliannjulianna
@user3114046, apologies for unchecking your reply as the answer as I found that R already has functions for it. see my answer below.Jeopardize
S
1

Best I found is:

readLines(rawConnection(as.raw(c(97,98,99,100,13))))

Although I guess it is better to close the connection

con = rawConnection(as.raw(c(97,98,99,100,13)))
res = readLines(con);
close(con);
show(res);

[1] "abcd"
Sourwood answered 17/4, 2014 at 2:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.