I want to coerce an object of class Raster Layer to class SpatialPixelsDataFrame since that is required as input for the function autoKrige from the r library automap. However, when I try to use as from the r library methods, I get the following error:

Encountered "as" at line 307, column 25. Was expecting one of ...

Where line 307 is:

layerGrid = methods.as(layerRaster, "SpatialPixels")

I'm assuming that the word as has already has a meaning in python. The question is, however, how do I use the function as. Is it possibly replaced by rpy2 with a different name?


Accessing R symbols in packages that are syntactically invalid in Python can be done through __dict__. Here:

r_as = methods.__dict__['as']

See the documentation for rpy2: http://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html#importing-r-packages


Found a work around, store the R function in a separate function:

                    asRaster <<- as(rasterAs, "SpatialPixels")

Retrieve the function from the R global environment and call it:

        setAs = r.globalenv['setAs']
        SpatialPixels = setAs(layerRaster)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.