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

2024-04-26 13:02:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是从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. 取消数据序列化

Tags: theto数据import目标字节bytesro
1条回答
网友
1楼 · 发布于 2024-04-26 13:02:24

R的serialize()返回字节向量列表。这是unserialize()所期望的输入。以下内容将“起作用”:

ro.r('unserialize')(r_res)

否则,构建rpy2Vector(对于RRAWSXP向量)可以像对于其他向量一样实现:

>>> 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'

相关问题 更多 >