簡體   English   中英

Rpy2:如何訪問 R 列表類型變量?

[英]Rpy2: how to access the R list-type variable?

我可以使用rpy2在 Jupyter/Python 中擬合模型,但是,返回的結果是 R 中的列表類型值。例如

# Cell #1, load rpy2 and re
%load_ext rpy2.ipython
%R require(ggplot2)
%R require(movMF)

# Cell #2, generate data from Python
from scipy.stats import vonmises
kappa = 5
samples = vonmises.rvs(kappa, size=100)
data = [cos(samples), sin(samples)]

# Cell #3, fit model using R and rpy2
%%R -i data -o result
result = movMF(data, 1, nruns = 10)

# Cell #4, print result
print(result)

結果如下所示:

在此處輸入圖片說明

如果我輸入result它會返回

R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]
  theta: <class 'rpy2.robjects.vectors.Matrix'>
  R object with classes: ('matrix',) mapped to:
<Matrix - Python:0x0000000004FCF388 / R:0x0000000010C5B2B8>
[5.235426, -0.023640]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4588 / R:0x0000000011F6B6B0>
[1.000000]
  L: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x00000000103B4BC8 / R:0x00000000114FB6F0>
[118.877731]
  ...
  theta: <class 'rpy2.robjects.vectors.IntVector'>
  R object with classes: ('integer',) mapped to:
<IntVector - Python:0x0000000011441248 / R:0x0000000011F6B980>
[       1]
  alpha: <class 'rpy2.robjects.vectors.FloatVector'>
  R object with classes: ('logLik',) mapped to:
<FloatVector - Python:0x00000000114415C8 / R:0x000000000EE447E0>
[118.877731]
R object with classes: ('movMF',) mapped to:
<ListVector - Python:0x00000000103B4448 / R:0x0000000010CB2380>
[Matrix, Float..., Float..., ..., IntVe..., Float..., ListV...]

我想知道,我怎樣才能訪問它的內在價值?

到目前為止,我只能玩result[0] ,不確定這是否是正確的方法。


在 R 環境中,這是數據結構:

在此處輸入圖片說明

我可以訪問像result$theta這樣的值

print(pamk_clusters$pamobject$clusinfo)

不會工作,它的等價物

print(pamk_clusters[["pamobject"]][["clusinfo"]])

也行不通……但是,在“人”中進行了一些挖掘之后

https://rpy2.github.io/doc/latest/html/vector.html#extracting-r-style

通過分別代表 R 函數 [ 和 [[ 的兩個委托者 rx 和 rx2 授予對 R 樣式提取/子集的訪問權限。

這按預期工作

print(pamk_clusters.rx2("pamobject").rx2("clusinfo"))

我在論壇中評論了“人”的清晰度:

https://bitbucket.org/rpy2/rpy2/issues/436/accessing-dataframe-elements-using-rpy2

我找到了兩種方法來做到這一點。 假設您的列表是:

a_list <- list(x1 = c(1,2,3), x2 = c(4,5,6))

您可以通過rpy2通過執行以下操作訪問a_list$x1

print(a_list.rx2('x1'))

或( https://rpy2.github.io/doc/latest/html/vector.html#assigning-r-style ):

print(a_list[a_list.names.index('x1')])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM