Search code examples
pythonrrpy2

Extracting returned value from rpy2


I am using a Jupyter notebook (Python 3 kernel) with rpy2 (V2.9.1) to run commands in R from Python. I can pass values to and from R, but my problem is I do not know how to extract the information I need from the variable returned from R. I have the following code:

%Rpush blood

%%R
library("mice")
memory.limit(56000)
imp <- mice(blood, seed = 23109)

%Rpull imp

print(imp)
[out]<rpy2.rinterface.ListSexpVector - Python:0x00000178FC1BDA20 / R:0x00000178BCF236F0>

imp is a list with 21 elements. I would like to be able to access the elements by name. According to this post: rpy2 access R named list items by name, low-level interface I should be able to do the following for example:

m = imp.rx('m')

or

 m = imp[imp.names.index('m')]

Both of these give the error message "'rpy2.rinterface.ListSexpVector' object has no attribute 'rx' (or 'names' in the 2nd case).Yet the post referenced above was using ListSexpVector. Is there a way of doing this?


Solution

  • I realised after reading this post: How to get data from R to pandas that the problem was with %Rpull. %Rpull does not return the object in a Python-friendly form, whereas using

    %%R -i blood -o imp
    

    does, and print(imp) then works as expected, as do the other operations listed in the question.