Works with Python and R

Think about how R and Python work together

Recently, about Basic data plotting and File input / output method by R explained.

There is a tendency to do everything with Python as a data analysis language, but it is still a huge past Assets from R are attractive and not so easily truncated.

A common case is when you want to use R for partial data analysis, but want to write the entire programming in Python. You may also want to do only plotting with R. In such a case, it would be convenient if Python and R could be linked to solve the problem at once.

Library PypeR that uses R from Python

It seems that a library called RPy2 was used in the past, but recently it has been used and the mainstream is [PypeR](http://www.webarray. org / softwares / PypeR /).

Install PypeR

Installation is easy. Install with the package manager pip.

pip install pyper

Pass data from Python to R

R source code

Consider the following code for R (scatter.R).

png("image.png ", width = 480, height = 480,
    pointsize = 12, bg = "white", res = NA)
plot(data$WRAIN, data$LPRICE2, pch=16,
     xlab="Rainfall from October to March of the previous year of harvest",
     ylab="Wine price")
dev.off()

This is a simple R source code that extracts two columns from data, plots them, and writes them to a .png file.

Python source code

Let's pass data to this R in Python and then retrieve the object to Python. The original data is a CSV file that stores the price of wine and can be viewed from here.

import pyper
import pandas as pd

#Read CSV data with Python
wine = pd.read_csv("wine.csv")

#Create an instance of R
r = pyper.R(use_pandas='True')

#Pass a Python object to R
r.assign("data", wine)

#Run the R source code
r("source(file='scatter.R')")

The contents of wine.csv read in Python are now passed to R and successfully plotted.

image.png

Read R objects from Python

Python source code

On the other hand, you may want to retrieve the result of R processing in Python. In such cases, you can retrieve the R object with the r.get method.

#Execute R code
r("res1 = cor.test(data$WRAIN, data$LPRICE2)")
r("data1 = subset(data, LPRICE2 < 0)")
r("res2 = cor.test(data1$WRAIN, data1$LPRICE2)")

#Read R objects in Python
res1 = pd.Series(r.get("res1"))
res2 = pd.Series(r.get("res2"))

print(res1)
#=>
#alternative                                  two.sided
#conf.int       [-0.258366126613384, 0.489798400688013]
#data.name                  data$WRAIN and data$LPRICE2
#estimate                                     0.1348919
#method            Pearson's product-moment correlation
#null.value                                           0
#p.value                                      0.5023297
#parameter                                           25
#statistic                                    0.6806807
#dtype: object

print(res2)
#=>
#alternative                                  two.sided
#conf.int       [-0.409535600260672, 0.364710477639889]
#data.name                data1$WRAIN and data1$LPRICE2
#estimate                                   -0.02636626
#method            Pearson's product-moment correlation
#null.value                                           0
#p.value                                      0.8982662
#parameter                                           24
#statistic                                   -0.1292127
#dtype: object

This time I used pandas, but this is not required. But being able to interact directly with R-like pandas objects is very helpful.

Summary

You can pass the data to R only when you need it, and then return the result as an object back to Python. It's much more convenient than writing the data to an external file once and running it separately. The assets of R can be used from Python, making Python more and more useful as a glue language.

reference

Try using R from Python with Python + PypeR http://mia-0032.hatenablog.jp/entry/2013/08/30/000000

I want to use R from Python-but RPy2 is no good- http://d.hatena.ne.jp/dichika/20130213/1360718736

Recommended Posts

Works with Python and R
Programming with Python and Tkinter
Encryption and decryption with Python
Python and hardware-Using RS232C with Python-
python with pyenv and venv
Communicate with FX-5204PS with Python and PyUSB
Shining life with Python and OpenCV
Robot running with Arduino and python
Install Python 2.7.9 and Python 3.4.x with pip.
Neural network with OpenCV 3 and Python 3
AM modulation and demodulation with python
[Python] font family and font with matplotlib
Scraping with Node, Ruby and Python
Scraping with Python, Selenium and Chromedriver
Scraping with Python and Beautiful Soup
JSON encoding and decoding with python
Hadoop introduction and MapReduce with Python
[GUI with Python] PyQt5-Drag and drop-
Hashing data in R and Python
Reading and writing NetCDF with Python
I played with PyQt5 and Python3
Reading and writing CSV with Python
Multiple integrals with Python and Sympy
Coexistence of Python2 and 3 with CircleCI (1.0)
Easy modeling with Blender and Python
Sugoroku game and addition game with python
FM modulation and demodulation with Python
Communicate between Elixir and Python with gRPC
Data pipeline construction with Python and Luigi
Calculate and display standard weight with python
FizzBuzz with Python3
Scraping with Python
Monitor Mojo outages with Python and Skype
Statistics with python
FM modulation and demodulation with Python Part 3
[Automation] Manipulate mouse and keyboard with Python
Scraping with Python
Passwordless authentication with RDS and IAM (Python)
Python with Go
Python installation and package management with pip
Using Python and MeCab with Azure Databricks
Capturing images with Pupil, python and OpenCV
Twilio with Python
Fractal to make and play with Python
A memo with Python2.7 and Python3 on CentOS
Integrate with Python
Play with 2016-Python
Use PIL and Pillow with Cygwin Python
AES256 with python
Tested with Python
Create and decrypt Caesar cipher with python
python starts with ()
CentOS 6.4 with Python 2.7.3 with Apache with mod_wsgi and Django
Reading and writing JSON files with Python
with syntax (Python)
I installed and used Numba with Python3.5
Tweet analysis with Python, Mecab and CaboCha
Traffic monitoring with Kibana, ElasticSearch and Python
FM modulation and demodulation with Python Part 2
Visualize point P that works with Python
Zundokokiyoshi with python