使用 rpy2 将 Python 二进制数据转换为 R

Convert Python binary data to R using rpy2

我的目标是从 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.

理想情况下我想实现以下目标

  1. 将原始数据返回到 R
  2. 反序列化数据

R 的 serialize() 正在返回一个字节向量列表。这是 unserialize() 期望的输入。以下将 "just work":

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'

我找到了以下适合我的作品:

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)