RPy2 Convert Dataframe to SpatialGridDataFrame

808 views Asked by At

how can a Dataframe be converted to a SpatialGridDataFrame using the R maptools library? I am new to Rpy2, so this might be a very basic question.

The R Code is: coordinates(dataf)=~X+Y

In Python:

import rpy2
import rpy2.robjects as robjects
r = robjects.r
# Create a Test Dataframe 
d = {'TEST': robjects.IntVector((221,412,332)), 'X': robjects.IntVector(('25', '31', '44')), 'Y': robjects.IntVector(('25', '35', '14'))}
dataf = robjects.r['data.frame'](**d)
r.library('maptools')
# Then i could not manage to write the above mentioned R-Code using the Rpy2 documentation

Apart this particular question i would be pleased to get some feedback on a more general idea: My final goal would be to make regression-kriging with spatial data using the gstat library. The R-script is working fine, but i would like to call my Script from Python/Arcgis. What do you think about this task, is this possible via rpy2?

Thanks a lot! Richard

1

There are 1 answers

2
lgautier On BEST ANSWER

In some cases, Rpy2 is still unable to dynamically (and automagically) generate smart bindings.

An analysis of the R code will help:

coordinates(dataf)=~X+Y

This can be more explicitly written as:

dataf <- "coordinates<-"(dataf, formula("~X+Y"))

That last expression makes the Python/rpy2 straigtforward:

from rpy2.robjects.packages import importr
sp = importr('sp') # "coordinates<-()" is there

from rpy2.robjects import baseenv, Formula
maptools_set = baseenv.get('coordinates<-')
dataf = maptools_set(dataf, Formula(' ~ X + Y'))

To be (wisely) explicit about where "coordinates<-" is coming from, use:

maptools_set = getattr(sp, 'coordinates<-')