当前位置:首页>python>reticulate:左手 Python 右手 R

reticulate:左手 Python 右手 R

  • 2026-10-11 08:04:25
reticulate:左手 Python 右手 R

reticulate是由 RStudio(现 Posit)开发的 R 包,可以让你同时使用 Python 和 R 语言处理数据,不需要手动转换变量,支持:

  • 导入 Python 模块(如 import("numpy"))

  • 运行 Python 代码字符串或脚本

  • 自动/手动转换、访问 R 与 Python 对象(data.frame ↔ pandas DataFrame 等)

安装

默认您应该已经安装好 R 、 python,知道 python 的安装路径

install.packages("reticulate")library(reticulate)

配置

目的是让其自动调用配置好的 python

# ### 检查是否已识别 Pythonpy_available()# 配置特定路径下的 pythonuse_python("/usr/bin/python3")# 也可以直接使用 conda环境,指定环境名use_condaenv("base")# Would you like to create a defaultPython environment for the reticulate package?(Yes/no/cancel) no# 查看当前的配置py_config()

Python 装包

py_install("pandas")py_install("numpy")

数据结构映射

R 对象

Python 对象

说明

logical

bool

TRUE→ True

integer/ numeric

int/ float

标量自动转换

character(1)

str

单字符串

vector

list

R 向量 → Python list

list()

dict或 list

命名 list → dict

data.frame

pandas.DataFrame

最常见、最重要

matrix

numpy.ndarray

二维数值矩阵

array

numpy.ndarray

多维数组

factor

pandas.Categorical

保留因子水平

实际使用

使用 RMarkdown 语法,指定当前cell代码块是 python 或 r

library(reticulate)# 在 R语法中调用 python 模块os <-import("os")os$listdir(".")

使用 Python 读取表格并进行整理

import pandas as pddf = pd.read_csv("gene.txt",sep="\t")# gene_id去除最后的_序号即为 contigdf['contig']= df['gene_id'].apply(lambda x:"_".join(x.split("_")[:-1]))df.head()#                    gene_id     gene  ...  gene_name                  contig# 0  sample1_1|k97_10342636_1      MGE...RepA_C  sample1_1|k97_10342636

使用 R 进行绘图,直接使用 Python 处理好的数据

library(gggenes)library(ggplot2)# 在 R 环境中调用 python的对象, 在 py 对象下ggplot(py$df,aes(  xmin = start,  xmax = end,  y = contig,  fill = gene))+geom_gene_arrow()+geom_gene_label(aes(label = gene))+scale_fill_brewer(palette ="Set3")
library(gggenes)library(ggplot2)# 在 R 环境中调用 python的对象, 在 py 对象下ggplot(py$df,aes(  xmin = start,  xmax = end,  y = contig,  fill = gene))+geom_gene_arrow()+geom_gene_label(aes(label = gene))+scale_fill_brewer(palette ="Set3")

﹀

﹀

﹀

关注美格科服公众号
最新最全的产品资讯一手掌握

致尊敬的您:

广东美格基因科技有限公司作为国家专精特新“小巨人”企业,始终致力于微生物组学、环境DNA检测、AI+合成生物学等领域的技术创新与产业化发展。
公司汇聚了由国际顶尖学者领衔的研发团队,搭建了多个省级工程技术研究中心与 Aivolution 进化加速器平台,主持十余项国家、省级重点科研项目,曾斩获全国创新创业大赛全国亚军。
目前,公司在微生物组科服、环境DNA检测、AI 合成生物学等领域保持国际领先,技术成果覆盖科研、医药、农业、生态等多个领域。
未来,美格基因将持续深耕前沿技术,以创新驱动发展,力争在国际舞台上占据一席之地。
如您有任何需求和疑问,欢迎随时咨询,美格基因竭诚为您服务!
固话:400-968-5700
客服QQ:811480176
邮箱:support@magigene.com
官网:http://www.magigene.com

最新文章

随机文章