rpy2 中的矩阵赋值
Matrix assignment in rpy2
使用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-style:
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
如何为这个矩阵的行、列赋值?
这通常应该在文档中描述。
如果以下内容没有回答问题,请告诉我们:http://rpy2.readthedocs.io/en/version_2.8.x/vector.html#assigning-r-style
使用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-style:
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
如何为这个矩阵的行、列赋值?
这通常应该在文档中描述。
如果以下内容没有回答问题,请告诉我们:http://rpy2.readthedocs.io/en/version_2.8.x/vector.html#assigning-r-style