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.
unlist() function in R Language is used to convert a list to vector.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With