reticulate - found it very Useful

COMBINE Python and R with reticulate


So what exactly does reticulate do? It’s goal is to facilitate interoperability between Python and R. 

It does this by embedding a Python session within the R session which enables you to call Python functionality from within R.


library(reticulate)

np <- import("numpy")

# the Kronecker product is my favourite matrix operation

np$kron(c(1,2,3), c(4,5,6))

## [1] 4 5 6 8 10 12 12 15 18


In the above code It import the numpy module which is a powerful package for all sorts of numerical computations. 

reticulate then gives us an interface to all the functions (and objects) from the numpy module. 

It is calling these functions just like any other R function and pass in R objects, 

reticulate will make sure the R objects are converted to the appropriate Python objects.


You can also run Python code through source_python if it’s an entire script or py_eval/py_run_string if it’s a single line of code. 

Any objects (functions or data) created by the script are loaded into your R environment. Below is an example of using py_eval.


data("mtcars")

py_eval("r.mtcars.sum(axis=0)")

## mpg   642.900

## cyl   198.000

## disp  7383.100

## hp   4694.000

## drat   115.090

## wt    102.952

## qsec   571.160

## vs    14.000

## am    13.000

## gear   118.000

## carb   90.000

## dtype: float64


Notice the use of the r. prefix in front of the mtcars object in the python code. The r object exposes the R environment to the python session, 

it’s equivalent in the R session is the py object. The mtcars data.frame is converted to a pandas DataFrame to which It then applied the sum function on each column.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了