Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load R's .rdata files into Python?

I am trying to convert one part of R code in to Python. In this process I am facing some problems.

I have a R code as shown below. Here I am saving my R output in .rdata format.

nms <- names(mtcars)
save(nms,file="mtcars_nms.rdata")

Now I have to load the mtcars_nms.rdata into Python. I imported rpy2 module. Then I tried to load the file into python workspace. But could not able to see the actual output.

I used the following python code to import the .rdata.

import pandas as pd
from rpy2.robjects import r,pandas2ri
pandas2ri.activate()

robj = r.load('mtcars_nms.rdata')
robj

My python output is

R object with classes: ('character',) mapped to:
<StrVector - Python:0x000001A5B9E5A288 / R:0x000001A5B9E91678>
['mtcars_nms']

Now my objective is to extract the information from mtcars_nms.

In R, we can do this by using

load("mtcars_nms.rdata");
get('mtcars_nms')

Now I wanted to do the same thing in Python.

like image 220
RSK Avatar asked Aug 07 '18 08:08

RSK


1 Answers

There is a new python package pyreadr that makes very easy import RData and Rds files into python:

import pyreadr

result = pyreadr.read_r('mtcars_nms.rdata')

mtcars = result['mtcars_nms']

It does not depend on having R or other external dependencies installed. It is a wrapper around the C library librdata, therefore it is very fast.

You can install it very easily with pip:

pip install pyreadr

The repo is here: https://github.com/ofajardo/pyreadr

Disclaimer: I am the developer.

like image 55
Otto Fajardo Avatar answered Sep 29 '22 09:09

Otto Fajardo