Search code examples
pythonrrpy2r-maptools

R maptools wrld_simpl in rpy2


In R:

import(maptools)
data(wrld_simpl)

In python rpy2, how do I access wrld_simpl? The following code (in Python) fails as follows...package "maptools" has no attribute wrld_simpl

maptools = importr('maptools')
data = DataFrame(maptools.wrld_simpl)

Just trying to understand rpy2 (and revisit R from university days)


Solution

  • Use rpy2.robjects.packages.data, as demonstrated in the rpy2 introduction:

    >>> from rpy2.robjects.packages import importr, data
    
    >>> maptools = importr('maptools')
    >>> spatial_df_r = data(maptools).fetch('wrld_simpl')['wrld_simpl']
    >>> spatial_df_r
    <rpy2.robjects.methods.RS4 object at 0x7ffa932b0cc0> [RTYPES.S4SXP]
    R classes: ('SpatialPolygonsDataFrame',)
    

    You also seem to be trying to convert the data to pandas.DataFrame. The slight issue is that the data is not a data frame, but a SpatialPolygonsDataFrame object. You can however convert it to a proper data.frame:

    >>> base = importr('base')
    >>> df_r = base.as_data_frame(spatial_df_r)
    >>> tuple(df_r.rclass)
    ('data.frame',)
    

    and then to pandas DataFrame:

    from rpy2.robjects import conversion
    from rpy2.robjects import default_converter, pandas2ri
    
    with conversion.localconverter(default_converter + pandas2ri.converter):
        df = conversion.rpy2py(df_r)
    

    where df is now a pandas DataFrame:

    >>> type(df)
    <class 'pandas.core.frame.DataFrame'>
    

    However, if you are using Jupyter, the conversion can be done much more easily with with -o option of rpy2 magic, see: using rpy2 in notebooks and rpy2.ipython.rmagic.