Refs:
The rPython
package allows calling Python from R. THe Python session that the package iniciates lives during the current R session.
The installation on Windows requires extra steps and they are explained here. The next code snippet was part of this process and only needs to be done once:
# install Rtools (if necessary)
install.packages("installr")
library(installr)
install.Rtools()
# install devtools (if necessary)
install.packages("devtools")
library(devtools)
# after download of the package & config/folder updates
# (check https://github.com/cjgb/rPython-win), execute:
install("C:/Users/jpn.INFORMATICA/Software/_Langs/rPython")
After that, we just need to import the package, as usual:
library(rPython)
## Loading required package: RJSONIO
An example of function definition and call:
python.exec("
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)
")
python.call("fact", 6)
## [1] 720
Lists are translated automatically:
python.call( "len", 1:3 )
## [1] 3
a <- 1:4
b <- 5:8
python.exec( "def concat(a,b): return a+b" )
python.call( "concat", a, b)
## [1] 1 2 3 4 5 6 7 8
We can assign values to python vars, and use them in method calls:
str <- "hello world"
python.assign( "a", str )
python.method.call( "a", "split", " " )
## [1] "hello" "world"
Python files can be loaded using python.load
.
We can also make imports:
python.exec( "import math" )
my_pi <- python.get( "math.pi" )
my_pi
## [1] 3.141593
A stats eg in which Python does a linear regression:
head(cars)
## speed dist
## 1 4 2
## 2 4 10
## 3 7 4
## 4 7 22
## 5 8 16
## 6 9 10
plot(cars, pch=20)
python.assign( "X", cars$speed )
python.assign( "Y", cars$dist )
python.exec("
import numpy as np
from sklearn import linear_model
X = np.reshape(X, (50,1)) # reshape to 50x1 vector
Y = np.reshape(Y, (50,1))
regr = linear_model.LinearRegression()
regr.fit(X, Y)
intcp = regr.intercept_[0]
coefs = regr.coef_[0][0]
")
intcp <- python.get( "intcp " )
coefs <- python.get( "coefs" )
abline(intcp, coefs, col="red", lwd=2)