Calculating correlation with rpy2

I spend some time trying to figure out how to use R via Rpy2. Here are a short python code that I used to calculate correlation using Rpy2

import rpy2.robjects as robjects

def get_rcorr(floatData, n_rows, method=”spearman”):

floatData: list of floats,
number of rows in the data matrix
Hmisc library needs to be loaded before calling this
function ( rcorr() comes from there)..
Library can be loaded with command:  robjects.r(“library(Hmisc)”)
v = robjects.FloatVector(floatData)
dm = robjects.r[‘matrix’](v, nrow = n_rows)
res = robjects.r.rcorr(dm, type=method)
return res

robjects.r(“library(Hmisc)”) # for rcorr()

print (get_rcorr([1.0,2.0,4.0,5.0,1.0,1.0,1.0,0.0], 4)

get_rcorr([1,2,4,5,1,1,1,0], 4) will create then matrix as follows

  1.0  1.0
  2.0  1.0
  4.0  1.0
  5.0  0.0

and calculate correlation (R, p) for that.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s