Reputation: 1193
My goal is to get bytes data from Python to R to unserialize
in R. The following code provides the test
import rpy2.robjects as ro
rcode = 'serialize(iris, NULL)'
r_res = ro.r(rcode)
print(type(r_res[0]))
# <class 'bytes'>
# Works up to here, not sure what how to get the 'bytes' type back into R
# Got 24 from the Rinternals.h file where it indicates RAWSXP
rawsxp_rinternals = 24
r_vec = ro.SexpVector(r_res[0], rawsxp_rinternals)
This yields the following error:
Error while converting to Bytes element 0.
Ideally I would want to achieve the following
Upvotes: 0
Views: 237
Reputation: 21
I found the following works for me:
R code:
library(stringi)
foo <- function(binary_data) {
typeof(binary_data) # raw
# to decode use rawToChar if encoding is utf-8
# or stri_conv(binary_data, "from_encoding", "to_encoding"), from the lib stringi
stri_conv(binary_data, "utf8") # "my text"
}
Python code:
import rpy2.robjects as ro
text = "my text"
binary = text.encode("utf8")
r_raw_vector = ro.rinterface.ByteSexpVector(binary)
ro.r.foo(data=r_raw_vector)
Upvotes: 1
Reputation: 11545
R's serialize()
is returning a list of byte vectors. This is the input expected by unserialize()
. The following will "just work":
ro.r('unserialize')(r_res)
Otherwise, building an rpy2 Vector
(for an R RAWSXP
vector) can be achieved like for other vectors:
>>> ro.rinterface.str_typeint(r_res.typeof)
'RAWSXP'
>>> r_res2 = ro.vectors.Vector(r_res)
>>> ro.rinterface.str_typeint(r_res2.typeof)
'RAWSXP'
>>> r_res3 = ro.vectors.Vector([r_res[0]])
>>> ro.rinterface.str_typeint(r_res3.typeof)
'RAWSXP'
Upvotes: 1