如何创建一个空 R 向量来添加新项目

我想在 Python 中使用 R,由模块 Rpy2提供。我注意到 R 具有非常方便的 []操作,通过这些操作可以提取特定的列或行。我如何通过 Python 脚本实现这样一个函数?

我的想法是创建一个 R 向量然后把这些想要的元素加到这个向量中这样最终的向量就和 R 中的一样了我创建了一个 seq()但它似乎有一个初始数字1所以最终的结果总是以数字1开始这不是我想要的。那么,还有更好的方法吗?

295877 次浏览

I pre-allocate a vector with

> (a <- rep(NA, 10))
[1] NA NA NA NA NA NA NA NA NA NA

You can then use [] to insert values into it.

You can create an empty vector like so

vec <- numeric(0)

And then add elements using c()

vec <- c(vec, 1:5)

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)

vec <- vector()

See also vector help

?vector

I've also seen

x <- {}

Now you can concatenate or bind a vector of any dimension to x

rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)

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

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)

To create an empty vector use:

vec <- c();

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:

vec <- c(vec, 1);

or, to add a string value "a"

vec <- c(vec, "a");