Last active
August 26, 2015 17:07
-
-
Save thekensta/d50fb023a362f1a1d99d to your computer and use it in GitHub Desktop.
IPython Rpy2 passing parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Quick summary to access stuff in R from ipython | |
# Useful link but summary somehwat buried | |
# http://rpy.sourceforge.net/rpy2/doc-2.4/html/interactive.html | |
import numpy as np | |
%load_ext rpy2.ipython | |
# %R [-i INPUT] [-o OUTPUT] [-n] [-w WIDTH] [-h HEIGHT] [-p POINTSIZE] | |
# [-b BG] [–noisolation] [-u {px,in,cm,mm}] [-r RES] [code [code ...]] | |
# %R - returns a value | |
# %%R - doesn't return a value (cell magic) | |
x = np.random.uniform(size=100) | |
y = np.random.uniform(size=100) | |
A = np.array([x, y]) | |
# covariance matrix in python | |
Cpy = np.cov(A) | |
Cpy.shape | |
# (2, 2) | |
# Try the same in R, sending 'A' to R and getting variable 'C' back | |
%R -i A -o C C <- cov(A) | |
# Ouch, Matrixes have different shapes | |
print(C.shape) | |
# (100, 100) | |
%R -i A -o C C <- cov(t(A)) | |
print(C.shape) | |
# (2, 2) | |
# PUSH and PULL variables to and from R | |
X = np.random.uniform(size=5) | |
%Rpush X | |
%R mean(X) | |
# array([ 0.5623669]) | |
%R Y <- rbeta(10, 5, 15) | |
%Rpull Y | |
print(Y.shape) | |
# (10,) | |
# GET to return the value, rather than create a variable (PULL) | |
Y2 = %Rget Y | |
print(Y2) | |
# [ 0.28380814 0.30925777 0.45507836 0.26457303 0.14935679 0.32539179 | |
# 0.41532512 0.26216892 0.25340409 0.36681474] | |
# prop.test(..) for a more complex example | |
# Returned results in mapped types | |
res = %R prop.test(c(21, 29), c(150, 170)) | |
type(res) | |
# rpy2.robjects.vectors.ListVector | |
# Printing works nicely | |
print(res) | |
# 2-sample test for equality of proportions with continuity correction | |
# data: c(21, 29) out of c(150, 170) | |
# X-squared = 0.35732, df = 1, p-value = 0.55 | |
# alternative hypothesis: two.sided | |
# 95 percent confidence interval: | |
# -0.11611290 0.05493643 | |
# sample estimates: | |
# prop 1 prop 2 | |
# 0.1400000 0.1705882 | |
# Access Items in the List | |
[s for s in res.names] | |
# ['statistic', | |
# 'parameter', | |
# 'p.value', | |
# 'estimate', | |
# 'null.value', | |
# 'conf.int', | |
# 'alternative', | |
# 'method', | |
# 'data.name'] | |
res.names.index('p.value') | |
# 2 | |
res[res.names.index('p.value')] | |
# <FloatVector - Python:0x10d3cc488 / R:0x7f9848809a08> | |
# [0.549997] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment