Created
March 28, 2018 15:33
-
-
Save mathurinm/99507ff7a4567318de73ba8eb513e6f1 to your computer and use it in GitHub Desktop.
Running R function with rpy2
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
# obtained with priceless help from Olivier Grisel | |
# rpy2 is available via pip: pip install rpy2 | |
import numpy as np | |
from rpy2 import robjects | |
import rpy2.robjects.packages as rpackages | |
from rpy2.robjects import numpy2ri | |
from rpy2.robjects import pandas2ri | |
# we use function ltsReg of package robustbase | |
if __name__ == "__main__": | |
X = np.random.rand(50, 20) | |
y = np.random.randn(50) | |
numpy2ri.activate() | |
pandas2ri.activate() | |
utils = rpackages.importr('utils') | |
utils.chooseCRANmirror(ind=1) # select the first mirror in the list | |
if not rpackages.isinstalled('robustbase'): | |
utils.install_packages("robustbase") | |
ltsReg = rpackages.importr('robustbase') | |
ltsReg = robjects.r['ltsReg'] | |
ltsReg_fit = ltsReg(X, y) | |
ltsReg_fit_dict = dict(zip(ltsReg_fit.names, list(ltsReg_fit))) | |
print("returned values: ", ltsReg_fit_dict.keys()) | |
as_matrix = robjects.r['as'] | |
# getting coefs: | |
raw_coef = robjects.r.coef(ltsReg_fit) | |
coefs = np.array(as_matrix(raw_coef, "matrix")) | |
# getting some other results: | |
residuals = np.array(as_matrix(ltsReg_fit_dict["residuals"], "matrix")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment