Hi, 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 a R vector and add those wanted elements into this vecotr so that the final vector is the same as that in R. As I am new to R, I create a seq(), but it seems that it has an initial digit 1, so the final result would always started with the digit 1, which is not what I want. So, is there a better way to do this? Thanks!
+3
A:
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.
Roman Luštrik
2010-08-05 11:06:43
You don't need `c()`. `a<-rep(NA, 10)` works. And one could force class of vector by using specific type of `NA`, e.g.: `rep(NA_integer_, 10)` (see `help("NA")`).
Marek
2010-08-05 11:52:39
Of course you could drop out c(), a senior moment on my part. Good info Marek, thank you.
Roman Luštrik
2010-08-05 12:30:13
Thank you! It works!
ligwin
2010-08-05 12:39:05
+1
A:
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)
Aaron Statham
2010-08-05 12:00:21
I like your solution with numeric(), but my experience has led me to use NA instead of 0 (if you use numeric(2), you will get 0 0). But that's my personal preference.
Roman Luštrik
2010-08-05 12:19:56
Many thanks!! But is it possible to free the previous one after the addition of one new element? should I simply use rm()?
ligwin
2010-08-05 12:41:35
There is another problem that typeof(numeric(0)) gives "double" whereas the wanted elements gives "integer", when added, a error was raised saying "The type for the new value cannot be different", how to convert?
ligwin
2010-08-05 12:53:53
when working in python, the "as" is a keyword, in addition, python do not have such data types, so I think "as.integer" won't work?
ligwin
2010-08-05 12:58:13
romunov - numeric(0) means create a numeric vector with length of 0 (ie no elements) not a vector of length 1 with that element being 0
Aaron Statham
2010-08-05 14:23:12
A:
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)
JoFrhwld
2010-08-05 18:27:09
A:
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
lgautier
2010-08-06 15:25:32