【发布时间】:2016-06-07 15:04:27
【问题描述】:
使用 rpy2,在 python 3.5 中,我可以定义一个 R 矩阵:
import rpy2.robjects as robjects
m = robjects.r.matrix(robjects.IntVector(range(10)), nrow=2, ncol = 5)
print(m)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 2 4 6 8
[2,] 1 3 5 7 9
然后我可以extract an element by row, column, R-style:
print(m.rx(1, 2))
[1] 2
我可以为任意元素赋值,Python 风格:
m[4] = 100
print(m.rx(1, 3))
[1] 100
但是,我不知道如何按行、列分配元素。我尝试了以下方法:
m.rx(1, 3) = 200
m.rx(1, 3) = 200
^
SyntaxError: can't assign to function call
和
m[0, 2] = 200
m[0, 2] = 200
File "/Users/xavier/python/3.5/lib/python3.5/site-packages/rpy2/robjects/vectors.py", line 261, in __setitem__
res = super(Vector, self).__setitem__(i, value)
TypeError: VectorSexp indices must be integers, not tuple
如何为该矩阵的行、列赋值?
【问题讨论】:
-
谷歌搜索
rpy2 rx建议m.rx[1, 3] = 200可能有用。
标签: python python-3.x rpy2