Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change column names of a dataframe using rpy2

Tags:

dataframe

r

rpy2

I want to do the equivalent of this R code:

m2 <- cbind(1,2)
colnames(m2) <- c("x","Y")

When I do

import rpy2.robjects as R
m2 = R.r['cbind'](1,2)
R.r['colnames'](m2) = R.StrVector(['x','y'])

I get this error:

SyntaxError: can't assign to function call

I tried

>>> m2 = R.r['colnames'](m2, R.StrVector(['x','y']))
>>> print m2

[1] "x1" "y2" 

And

>>> params = {'do.NULL':False}
>>> m2 = R.r['colnames'](R.StrVector(['x','y']), m2, **params)
>>> print m2

[1] "11" "21"

Which both don't give the result that I want. So how can I use colnames to change the column names of a dataframe?

like image 889
Niek de Klein Avatar asked Sep 19 '25 23:09

Niek de Klein


1 Answers

If anyone wants to know, the answer is:

m2.colnames = R.StrVector(['x','y']) 
like image 84
Niek de Klein Avatar answered Sep 22 '25 12:09

Niek de Klein