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

使用Reticulate在R中调用pyts的变量传递与提取问题

问题解决方法

1. 解决R变量无法传入Python的报错

  • 触发NameError: name 'x' is not defined的核心原因是repl_python()启动的交互式Python会话不会默认同步R全局环境的变量,同时你定义的x是tibble格式,不符合pyts输入要求:
    • 访问R侧变量可以直接在Python代码中加r.前缀调用,不需要提前同步
    • pyts的fit_transform要求输入为形状(n_samples, n_timestamps)的二维数值数组,tibble需要转成矩阵格式才能正常传入

2. 解决Python变量提取到R的问题

  • 你原本用py$变量名的调用方式完全正确,只要Python会话中生成的变量没有被销毁,都可以通过py对象直接读取,导入模块时设置的convert=TRUE会自动把Python数组转成R兼容的格式,无需额外转换。

修正后可运行的完整代码

require(reticulate); require(tibble)
pyts<- reticulate::import("pyts", convert = TRUE)
pytsImage<-reticulate::import("pyts.image", convert = TRUE)
# 提前转成矩阵符合pyts输入要求
x <- as.matrix(tibble(values = sin(-10:6)))

repl_python()
from pyts.image import GramianAngularField
gasf = GramianAngularField(image_size=17, method='summation')
# 用r.前缀调用R侧的x变量
X_gasf = gasf.fit_transform(r.x)
gadf = GramianAngularField(image_size=17, method='difference')
X_gadf = gadf.fit_transform(r.x)
exit

# 直接读取Python变量到R环境
r_X_gasf <- py$X_gasf
r_X_gadf <- py$X_gadf

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:45:00