将元素(向量)添加到 rpy2 的列表中
在 R 中,我可以轻松地将元素添加到列表中:
mylist = list()
mylist[[1]] = c(1,2)
mylist[[2]] = c(2,3)
mylist[[length(mylist)+1]] = c(3,4)
How do I do this in rpy2?我正在使用 rpy2 2.1.9。我尝试了以下方法,但它不起作用
import rpy2.robjects as robjects
a = robjects.r('list()')
b = robjects.IntVector([1,2])
a[0] = b
IndexError: Index out of range.
a[1] = b
IndexError: Index out of range.
aa = a.__add__(b) # But this makes a list out of the vector
aa.r_repr()
'list(1L, 2L)'
# We wanted something like the following instead:
aaa = robjects.r('list(c(1,2))')
aaa.r_repr()
'list(c(1, 2))'
In R, I can add elements to a list easily:
mylist = list()
mylist[[1]] = c(1,2)
mylist[[2]] = c(2,3)
mylist[[length(mylist)+1]] = c(3,4)
How do I do this in rpy2? I am using rpy2 2.1.9. I tried the following but it doesn't work
import rpy2.robjects as robjects
a = robjects.r('list()')
b = robjects.IntVector([1,2])
a[0] = b
IndexError: Index out of range.
a[1] = b
IndexError: Index out of range.
aa = a.__add__(b) # But this makes a list out of the vector
aa.r_repr()
'list(1L, 2L)'
# We wanted something like the following instead:
aaa = robjects.r('list(c(1,2))')
aaa.r_repr()
'list(c(1, 2))'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想使用 R 的“[[<-”运算符,你必须调用方法 rx2()
(参见[分配,R 风格][1])。
在 rpy2-2.2.0dev 中,您可以执行
a.rx2[1] = b
。[1]: http://rpy.sourceforge .net/rpy2/doc-2.2/html/vector.html#assigning-r-style 分配,R 风格
If you want to use R's "[[<-" operator, you'll have to call the method rx2()
(see [assigning, R-style][1]).
In rpy2-2.2.0dev, you can do
a.rx2[1] = b
.[1]: http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#assigning-r-style assigning, R-style
我不确定您是否可以使用当前版本的 rpy2 来执行此操作,但您可以尝试 rpy2.rlike.container.TaggedList 类,它可以充当 R 列表并支持附加、删除和重新标记项目。据我所知,列表和向量的分配中一定存在错误。
I'm not sure that you can do this with the current version of rpy2, but you can try out the rpy2.rlike.container.TaggedList class, which can act as an R list and supports appending, removing and retagging items. As far as I can tell, there must be a bug in the assignment for lists and vectors.