Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a `raw` into a vector of integers in R?

Tags:

r

I need to pass a raw back to Java via JRI, but it doesn't support raws, only various other vector types (such as integers). How do I convert a raw (vector of bytes) into a vector of integers?

I tried passing the data back as a vector of strings, but that breaks because JRI doesn't decode the string properly (eg '\x89' gets discarded as "").

Would also be nice if it were more efficient (unboxed). as.integer does not work - it doesn't return the byte values of the characters in the array, not to mention the fact that rawToChar produces "" for nuls.

like image 951
Yang Avatar asked Aug 24 '11 06:08

Yang


People also ask

How do I convert something to a vector in R?

unlist() function in R Language is used to convert a list to vector.

How do I turn an integer into a vector in R?

To convert a given character vector into integer vector in R, call as. integer() function and pass the character vector as argument to this function. as. integer() returns a new vector with the character values transformed into integer values.

How do I turn a row into a Dataframe vector?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

What is a raw vector?

A raw vector is used to represent a "raw" sequence of bytes. Each byte is a value between 0 and 255. There are no NA values. Raw vectors are printed using hexadecimal (base 16) notation, so the (decial) value code10 is printed as 0a.


2 Answers

Taking this a stage further, you can readBin directly from a raw vector. So we can:

> raw
[1] 2b 97 53 eb 86 b9 4a c6 6c ca 40 80 06 94 bc 08 3a fb bc f4
> readBin(raw, what='integer', n=length(raw)/4)
[1]  -346843349  -968181370 -2143237524   146576390  -188941510  
like image 74
dsz Avatar answered Nov 01 '22 11:11

dsz


This question is pretty old, but for those who (like myself) came across this while searching for an answer: as.integer(raw.vec) works well.

f <- file("/tmp/a.out", "rb")
seek(f, 0, "end")
f.size <- seek(f, NA, "start")
seek(f, 0, "start")
raw.vec <- readBin(f, 'raw', f.size, 1, signed=FALSE)
close(f)
bytes <- as.integer(raw.vec)
like image 27
mkfs Avatar answered Nov 01 '22 10:11

mkfs