pyreadr not working (how to import RData file to python)

Question:

I always get an empty dictionary when I import any RData file into Python using pyreadr. Here is my Python code:

import pyreadr

result = pyreadr.read_r('data.RData')
print(result.keys())

which returns

odict_keys([])

I have pyreadr installed and am running Python version 3.7.11 on Mac. In the above example I generated the RData file ‘data.RData’ in RStudio as follows:

x <- c(0.20,0.30,0.27,0.23)
data <- list("a", 5.1, x)
save(data, file="data.RData")

I’m sure ‘data.RData’ is in the right directory. What’s going wrong?

Asked By: user1222

||

Answers:

Nothing is going wrong: lists are not supported by pyreadr.

See the documentation section What objects can be read and written.

Answered By: neilfws

You can use the package rdata instead. It allows lists and S4 objects, and it is written in pure Python (so you can easily install it everywhere):

import rdata

parsed = rdata.parser.parse_file("data.RData")
converted = rdata.conversion.convert(parsed)
print(converted)
{'data': [['a'], array([5.1]), array([0.2 , 0.3 , 0.27, 0.23])]}

Disclaimer: I am the author of the rdata package.

Answered By: Mabus
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.