Reticulate

R? Python?

My main language for data analysis is R, but sometimes Python is used for its convenience. I wanted to find a way of using both language interactively in R, and this article is the introduction of a R package, “Reticulate,” which allows us to use both language in R.

Reticulate

The R package, “Reticulate,” is quite recent package published in July 2019. It is still being updated for some issues, but it’s useful if you want use Python modules in R. You can see and download a cheat sheet published in R website, Here.

I performed simple decision tree and XGBoost with Bayesian Optimization with both languages, R and Python, through “Reticulate” package in R, and it works successfully.

For the preparateion to use Reticulate, you have to install or update your R, Rstudio, pip, conda, and Python as the recent version.

You start with installing “reticulate” package in R by

1
2
install.packages("reticulate")
library(reticulate)

And, you can create your virtual environment locally, and make sure you have installed all modules of Python you will use in the environment.

Creation your Python virtual environment with

1
virtualenv_create(envname = "yourname")

Or, you can just use the environment that is already set up in local. Once you have create the environment, then you can see the list of environments with

1
virtualenv_list()

And, you install the python modules into the virtual environment from your local conda or python environment. When you install those Python modules in virtual environment, you have to restart R and make sure the modules that you are going to use has been installed in your virtual environment by

createPythonEnv}
1
2
3
4
5
6
7
8
9
10
11
12
#virtualenv_install("r-reticulate", "bayesian-optimization")
#virtualenv_install("r-reticulate", "pandas")
#virtualenv_install("r-reticulate", "seaborn")
#virtualenv_install("r-reticulate", "sklearn")
#virtualenv_install("r-reticulate", "xgboost")
use_virtualenv("r-reticulate")

py_module_available("seaborn")
py_module_available("sklearn")
py_module_available("pandas")
py_module_available("bayes_opt")
py_module_available("xgboost")

Below is the implementation for simple decision tree in R.

Here is the implementation for simple decision tree with Python Virtual Envrionment in R.

You have to declare that you will be using Python environment by

1
repl_python()

Or, if you are using rMarkdown, then you make chunk with

Performing simple decision tree with Python virtual environment.

You can bring the R objects into Python environment by

1
r.yourobjects

After you are done with Python environment, you call the following codes in your console

You can also bring the Python objects into R environment by

1
py$yourobjects

Here is the full implemented codes for the “reticulate” package.

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×