如何创建空 R 向量来添加新项目
我想在 Python 中使用 R,如 Rpy2 模块提供的那样。我注意到 R 有非常方便的 []
操作,您可以通过它提取特定的列或行。如何通过Python脚本实现这样的功能呢?
我的想法是创建一个 R 向量并将那些想要的元素添加到这个向量中,以便最终的向量与 R 中的相同。我创建了一个 seq() ,但它似乎有一个初始数字1,所以最终结果总是以数字1开头,这不是我想要的。那么,有更好的方法吗?
I want to use R in Python, as provided by the module Rpy2. I notice that R has very convenient []
operations by which you can extract the specific columns or lines. How could I achieve such a function by Python scripts?
My idea is to create an R vector and add those wanted elements into this vector so that the final vector is the same as that in R. I created a seq()
, but it seems that it has an initial digit 1, so the final result would always start with the digit 1, which is not what I want. So, is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
另请参阅矢量帮助
See also vector help
我预先分配了一个向量
,然后可以使用 [] 向其中插入值。
I pre-allocate a vector with
You can then use [] to insert values into it.
您可以像这样创建一个空向量
然后使用 c() 添加元素
但是正如 romunov 所说,最好预先分配一个向量然后填充它(因为这可以避免每次添加元素时重新分配向量的新副本)
You can create an empty vector like so
And then add elements using c()
However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)
要创建空向量,请使用:
请注意,我不会对您所需的向量类型(例如数字)做出任何假设。
创建向量后,您可以按如下方式向其中添加元素:
例如,添加数值 1:
或者添加字符串值“a”
To create an empty vector use:
Please note, I am not making any assumptions about the type of vector you require, e.g. numeric.
Once the vector has been created you can add elements to it as follows:
For example, to add the numeric value 1:
or, to add a string value "a"
我还看到
现在您可以将任何维度的向量连接或绑定到
x
I've also seen
Now you can concatenate or bind a vector of any dimension to
x
正如 Brani 所指出的,vector() 是一个解决方案,例如
newVector <- vector(mode = "numeric", length = 50)
将返回一个名为 "newVector" 且有 50 个“0”的向量为初始值。将新标量添加到现有向量以获得扩展向量也是相当常见的,例如
aVector <- c(aVector, newScalar)
As pointed out by Brani, vector() is a solution, e.g.
newVector <- vector(mode = "numeric", length = 50)
will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.
aVector <- c(aVector, newScalar)
在 rpy2 中,使用 R 获得与“[”完全相同的运算符的方法是使用“.rx”。
请参阅有关使用 rpy2 提取的文档< /a>
对于创建向量,如果您了解 Python 的使用方法,那么就不会有任何问题。
请参阅有关创建向量的文档
In rpy2, the way to get the very same operator as "[" with R is to use ".rx".
See the documentation about extracting with rpy2
For creating vectors, if you know your way around with Python there should not be any issue.
See the documentation about creating vectors