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")