📰 来源: 博客园
一、重要的桥接Python库
rpy2# pip install rpy2 我的R语言版本为 4.1.3 ,需要rpy2 3.5.X版本去对应
确保你电脑已安装 R,并在 R 里装好相关包:# install.packages(c("ggplot2", "ggstatsplot", "patchwork","ggpmisc"))
注意:这里可能遇到几个问题:
1.rpy2同python同R的版本兼容问题
可能有报错:ffi.error: symbol 'R_getVar' not found in library 'E:\R\Rlangrage\R-4.1.3\bin\x64\R.dll': error 0x7f
此时需要调整rpy2版本使得三方同时适配
2.R中没有相关的库/包
可能有报错:rpy2.robjects.packages.PackageNotInstalledError: The R package "ggplot2" is not installed.
install.packages("https://cran.r-project.org/src/contrib/Archive/ggplot2/ggplot2_3.4.2.tar.gz", repos = NULL, type = "source")
可能有报错:rpy2.rinterface_lib.embedded.RRuntimeError: Error in library(ggstatsplot) : there is no package called 'ggstatsplot'
方法:安装兼容 R 4.1.3 的旧版 ggstatsplot
一般方法较为困难,这里采用屏幕快照,穿越回4.1.3适用的当年进行下载:
①打开 R 4.1.3 控制台,先设置镜像为 MRAN 快照(这里选择 2022-08-15,R 4.1.3 稳定期):
options(repos = c(CRAN = "https://cran.microsoft.com/snapshot/2022-08-15/"))
②直接安装 ggstatsplot、ggpmisc
,它会自动从该快照拉取兼容版本的依赖包(correlation, datawizard, patchwork 等全部是当时的老版本)
install.packages("ggstatsplot")
③如果提示需要 Rtools 编译(Windows 下极少发生,快照提供二进制),就先装 Rtools40,安装时勾选“Add Rtools to system PATH”。
备用:如果 MRAN 快照连接失败,可改用其它历史镜像,例如:
options(repos = c(CRAN = "https://packagemanager.rstudio.com/cran/__linux__/focal/2022-08-15"))
options(repos = c(CRAN = "https://packagemanager.posit.co/cran/2022-08-15"))
当报错:Warning: unable to access index for repository https://cran.microsoft.com/snapshot/2022-08-15/src/contrib: 无法打开URL'https://cran.microsoft.com/snapshot/2022-08-15/src/contrib/PACKAGES'即表示该快照或穿越路线失效需要更换快照路径
可能有报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb2 in position 32: invalid start byte
方法:在 Python 中强制 R 使用英文消息声明:
在导入 rpy2 后、任何绘图前,加一行:
ro.r('Sys.setenv(LANGUAGE="en")')
例 1:ggstatsplot —— 一行代码带统计检验的箱线图
点击阅读原文
文章评论