views:

231

answers:

5

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
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
Of course you could drop out c(), a senior moment on my part. Good info Marek, thank you.
Roman Luštrik
Thank you! It works!
ligwin
+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
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
Many thanks!! But is it possible to free the previous one after the addition of one new element? should I simply use rm()?
ligwin
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
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
Okay, I finally got it and work it out!! thanks!!
ligwin
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
A: 
vec <- vector()

See also vector help

?vector
Brani
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
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
Thank you! That will be very helpful, thanks indeed!
ligwin
I used to create a function in python for this purpose, which is very complicated and I am not sure how widely it could apply. Now I think with this operators, life could be much easier:)
ligwin