【问题标题】:Rpy2: how to access the R list-type variable?Rpy2:如何访问 R 列表类型变量?
【发布时间】:2018-01-11 20:08:31
【问题描述】:

我可以使用 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这样的值

【问题讨论】:

    标签: python r rpy2


    【解决方案1】:

    我发现了两种方法。 假设您的列表是:

    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')])
    

    【讨论】:

      【解决方案2】:
      print(pamk_clusters$pamobject$clusinfo)
      

      不起作用,它的等价物

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

      也行不通...但是,在“男人”中进行了一些挖掘之后

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

      通过两个委托人 rx 和 rx2 授予对 R 样式提取/子集的访问权限,分别代表 R 函数 [ 和 [[。

      这按预期工作

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

      我在论坛上评论过“人”的清晰度:

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

      【讨论】:

        猜你喜欢
        • 2012-07-29
        • 2013-12-15
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 2018-02-11
        • 2013-12-24
        • 1970-01-01
        • 2019-01-27
        相关资源
        最近更新 更多