我的目标是将字节数据从Python传递到R到R中的unserialize
。以下代码提供了测试
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)
这会产生以下错误:
Error while converting to Bytes element 0.
理想情况下,我希望实现以下目标
答案 0 :(得分:1)
R&#39; s serialize()
正在返回字节向量列表。这是unserialize()
期望的输入。以下将&#34;只是工作&#34;:
ro.r('unserialize')(r_res)
否则,构建rpy2 Vector
(对于R RAWSXP
向量)可以像其他向量一样实现:
>>> 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'
答案 1 :(得分:1)
我为我找到了以下作品:
R代码:
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代码:
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)