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.

Published by lankoski

Petri Lankoski, D.Arts, is a Associate Professor in Game Studies at the school of Communication, Media and IT at the Södertörn University, Sweden. His research focuses on game design, game characters, role-playing, and playing experience. Petri has been concentrating on single-player video games but researched also (multi-player) pnp and live-action role-playing games. This blog focuses on his research on games and related things.

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: