Search code examples
pythonrdataframerpy2

how to select columns from R dataframe in rpy2 in python?


I have a dataframe in rpy2 in python and I want to pull out columns from it. What is the rpy2 equivalent of this R code?

df[,c("colA", "colC")]

this works to get the first column:

mydf.rx(1)

but how can I pull a set of columns, e.g. the 1st, 3rd and 5th?

mydf.rx([1,3,5])

does not work. neither does:

mydf.rx(rpy2.robjects.r.c([1,3,5]))


Solution

  • I think the answer is:

    # cols to select
    c = rpy2.robjects.IntVector((1,3))
    # selection from df
    mydf.rx(True, c)