You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Jupyter Notebook中用rpy2与R Magic加载R库时遇值错误

解决Jupyter Notebook中rpy2加载R包时的ValueError问题

问题场景

在Jupyter Notebook中使用%%R魔法命令加载多个R包时触发错误,代码如下:

%%R 
# Load libraries from correct lib Paths for my environment - ignore this!
 .libPaths(.libPaths()[c(3,2,1)])

# Load all the R libraries we will be using in the notebook

library(scran)
library(RColorBrewer)
library(slingshot)
library(monocle)
library(gam)
library(BiocParallel)
library(ggplot2)
library(plyr)
library(MAST)

错误信息

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File /opt/anaconda3/envs/tsc-env/lib/python3.9/site-packages/rpy2/rinterface_lib/conversion.py:179, in _get_cdata(obj)
    178 try:
--> 179     cdata = obj.__sexp__._cdata
    180 except AttributeError:

AttributeError: 'numpy.str_' object has no attribute '__sexp__'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 get_ipython().run_cell_magic('R', '', '# Load libraries from correct lib Paths for my environment - ignore this!\n .libPaths(.libPaths()[c(3,2,1)])\n\n# Load all the R libraries we will be using in the notebook\n\nlibrary(scran)\nlibrary(RColorBrewer)\nlibrary(slingshot)\nlibrary(monocle)\nlibrary(gam)\nlibrary(BiocParallel)\nlibrary(ggplot2)\nlibrary(plyr)\nlibrary(MAST)\n#library(Seurat)\n#library(scater)\n#library(scDblFinder)\n#library(sctransform)\n#library(scry)\n#library(clusterExperiment)\n')

File /opt/anaconda3/envs/tsc-env/lib/python3.9/site-packages/IPython/core/interactiveshell.py:2517, in InteractiveShell.run_cell_magic(self, magic_name, line, cell)
   2515 with self.builtin_trap:
   2516     args = (magic_arg_s, cell)
--> 2517     result = fn(*args, **kwargs)
   2519 # The code below prevents the output from being displayed
   2520 # when using magics with decorator @output_can_be_silenced
   2521 # when the last Python token in the expression is a ';'.
   2522 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File /opt/anaconda3/envs/tsc-env/lib/python3.9/site-packages/rpy2/ipython/rmagic.py:935, in RMagics.R(self, line, cell, local_ns)
...
    182                          'to map it to one: %s' % repr(obj))
    183 else:
    184     cdata = cls(obj)

ValueError: Not an rpy2 R object and unable to map it to one: np.str_('value')

解决方案

以下是几种可行的修复方法,按优先级尝试:

1. 禁用rpy2的自动类型转换

这个错误的核心是rpy2在转换R输出到Python对象时,误处理numpy字符串类型导致的。可以通过两种方式禁用自动转换:

  • 方式一:给R魔法命令加-n参数
    修改代码为:

    %%R -n
    .libPaths(.libPaths()[c(3,2,1)])
    library(scran)
    library(RColorBrewer)
    library(slingshot)
    library(monocle)
    library(gam)
    library(BiocParallel)
    library(ggplot2)
    library(plyr)
    library(MAST)
    

    -n参数表示不进行R与Python对象的自动转换,规避类型转换错误。

  • 方式二:全局禁用转换
    在运行%%R代码前,先执行以下Python代码:

    import rpy2.robjects as ro
    ro.conversion.set_default_conversion(ro.conversion.get_conversion())
    

2. 调整.libPaths()的使用方式

避免动态排序.libPaths的返回值,改为直接指定明确的库路径。先查看当前库路径:

%%R
print(.libPaths())

再将输出的路径按需求手动写入:

%%R
.libPaths(c("/path/to/your/lib3", "/path/to/your/lib2", "/path/to/your/lib1"))
# 后续加载包代码不变

3. 排查冲突的R包

逐个加载包,定位触发问题的包:

%%R -n
.libPaths(.libPaths()[c(3,2,1)])
library(scran)  # 运行无错误后再加载下一个包

找到问题包后,可尝试加载时抑制输出:library(package, quietly=TRUE)。

4. 修复版本兼容性

该错误常出现在rpy2 3.x与高版本numpy(如1.24+)的组合中,可降级指定兼容版本:

pip install numpy==1.23.5 rpy2==3.5.1

安装完成后重启Jupyter内核。

5. 重置Jupyter环境

重启Jupyter Notebook内核,清除环境残留后重新运行加载包代码。

内容的提问来源于stack exchange,提问作者Skim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:02:15