A Few Days of Python: Using R in Python

Using R Functions in Python

import pandas as pd
import pyper as pr

def zone_func(zone_file):

    # IMPORT DATA:
    dat = pd.read_csv(zone_file, parse_dates=["Row Labels"])

    # CREATE A R INSTANCE WITH PYPER:    
    r = pr.R()
    
    # PASS DATA FROM PYTHON TO R:
    r.assign("rsfores", dat["forest"]) 
    
    # RUN R COMMANDS 
    forecast = r("""
            library(forecast)
            forecast_func <- function(vehicle){
                a_fit <- auto.arima(vehicle)
                a_forecast <- forecast(a_fit, h = 8)
                a_accuracy <- accuracy(a_forecast)
            }

            fores_output = forecast_func("rsfores")
    """)

    #  EXTRACT R OBJECT AS PANDAS DATA FRAME 
    pydata = pd.DataFrame(r.get("fores_output"))
    print pydata

zone_func("File_Atlanta.csv")
Advertisements

3 thoughts on “A Few Days of Python: Using R in Python

  1. Pingback: Distilled News | Data Analytics & R

  2. Pingback: A Few Days of Python: Using R in Python | Mubashir Qasim

  3. Any comments on how this compares to a subprocess call to R which loads the data in-situ? Presumably you would be doing this when you manipulate the data in python between loading and calling R, but it’s only one more write to use the subprocess method.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s