gpt4 book ai didi

python - rpy2:如何从调用 R 函数中获取返回值

转载 作者:太空宇宙 更新时间:2023-11-04 05:06:25 26 4
gpt4 key购买 nike

我想在 Python 中使用以下 R 脚本:

> library(bfast)
> apple <- read.csv("/Users/nskalis/Downloads/R/apple.csv", sep = ";", header=TRUE)
> data = apple
# data$in_bps: is vector of double numbers
> data.ts <- ts(data$in_bps, frequency=1)
> data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)
> data.fit$output[[1]]$Tt
> data.fit$output[[1]]$Vt.bp
> data.fit$output[[1]]$ci.Vt
> data.fit$output[[1]]$ci.Vt$confint

因此我正在使用 rpy2 并且我做了以下事情:

from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
importr("bfast")
data = range(1,100)
data = robjects.FloatVector(data)
data = robjects.r.ts(data, frequency=1)
x = robjects.r.bfast(data, h=0.1, season="none", max_iter=1)

结果变量x 等于

In [42]: x
Out[42]:
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
Yt: <class 'rpy2.robjects.vectors.FloatVector'>
R object with classes: ('ts',) mapped to:
<FloatVector - Python:0x7f234fd22dc8 / R:0x7605740>
[1.000000, 2.000000, 3.000000, ..., 97.000000, 98.000000, 99.000000]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]
...
Yt: <class 'rpy2.robjects.vectors.FloatVector'>
R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x7f234c053388 / R:0x586b668>
[0.000000]
output: <class 'rpy2.robjects.vectors.BoolVector'>
R object with classes: ('logical',) mapped to:
<BoolVector - Python:0x7f234c04eac8 / R:0x57ee518>
[NA]
R object with classes: ('bfast',) mapped to:
<ListVector - Python:0x7f234f7ad6c8 / R:0x76a2d60>
[Float..., ListV..., ListV..., ..., Float..., BoolV..., ListV...]

请问如何获取变量data.fit$output[[1]]$Vt.bp

PS:这是我第一次使用rpy2,所以如果我做错了什么,请随时告诉我。

最佳答案

如上所示,bfast方法显然返回一个嵌套对象,其中包含多层数据项。此外,返回的 Python 对象属于外部类 <class 'rpy2.robjects. vectors.ListVector'>带有嵌套的未命名元素。

作为按整数位置挖掘 Python 对象的替代方法,考虑使用匿名包导入工具导入用户定义的 R 函数,STAP ,它允许您保留 R 代码并使用 R 的命名元素命名法专门返回您需要的变量:

from rpy2.robjects.packages import STAP

r_fct_string ='''
bfast_out <- function(path){
data <- read.csv(path, sep = ";", header=TRUE)

data.ts <- ts(data$in_bps, frequency=1)
data.fit <- bfast(data.ts, h=0.1, season="none", max.iter=1)

data.fit$output[[1]]$Vt.bp
}
'''

r_pkg = STAP(r_fct_string, "r_pkg")

Vt_bp = r_pkg.bfast_out("/Users/nskalis/Downloads/R/apple.csv")

print(Vt_bp)

关于python - rpy2:如何从调用 R 函数中获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44353019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com