Rpy2:如何访问R list-type变量?

时间:2017-08-04 02:37:11

标签: python r rpy2

我可以使用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)

结果如下:

enter image description here

如果我输入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环境中,这是数据结构:

enter image description here

我可以访问result$theta

之类的值

2 个答案:

答案 0 :(得分:5)

print(pamk_clusters$pamobject$clusinfo)

将无效,及其等效

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

也行不通......但是,经过一些挖掘&#34; man&#34;

http://rpy2.readthedocs.io/en/version_2.7.x/vector.html#extracting-r-style

通过两个代理rx和rx2授予对R风格提取/子集的访问权限,代表R函数[和[[分别。

这可以按预期工作

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

我在论坛中评论过&#34; man&#34;净度:

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

答案 1 :(得分:1)

我找到了两种方法。 假设您的列表是:

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

您可以通过a_list$x1访问rpy2

print(a_list.rx2('x1'))

或(http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#assigning-r-style):

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