How to extract 'RS4' element in Rpy2

天大地大妈咪最大 提交于 2020-04-30 16:02:43

问题


I’m a Chinese reader of book “Applied Spatial Data Analysis with R”, which is very useful for spatial analysis work. I tried to translate the R code into python with the Rpy2, since python can handle more complex data sources. But I have a problem with the Rpy2 code. The NY8 data is attached with the email. The R code is:

library(rgdal)
NY8<-readOGR(".","NY8_utm18")
Syracuse<-NY8[NY8$AREANAME=="Syracuse city",]
Sy2_nb<-poly2nb(Syracuse,queen=FALSE)
library(spdep)
Sy2_nb<-poly2nb(Syracuse,queen=FALSE)
Sy2_lw<-nb2listw(Sy2_nb)
moran.plot(NY$POP8,Sy2_lw)

When I translate it with Rpy2, the code is:

>>> from rpy2.robjects.packages import importr
>>> utils = importr('utils')
>>> utils.install_packages('rgdal')
>>> rgdal=importr('rgdal')
>>> import os
>>> os.chdir("C:\\PYDATA\\NY")
>>> NY8=rgdal.readOGR(".","NY8_utm18")
>>> print(robjects.r['summary'](NY8))

When I want to translate the code “Syracuse<-NY8[NY8$AREANAME=="Syracuse city",] ”, for example:

>>>Syracuse=NY8[NY8$AREANAME=="Syracuse city",]

The error message is shown: SyntaxError: invalid syntax It seems I could not extract the “AREANAME” through “$”, because “$” is illegal in python.


回答1:


Use the method rx2 (https://rpy2.github.io/doc/latest/html/vector.html#extracting-r-style):

NY8.rx2("AREANAME")

If this an S4 object (your comment suggests so), a simple way to proceed is to fetch the generic "$" and use it as a function.

base = importr("base")
# "$" is not a syntactically valid name for a Python function,
# so we fetch it form the instance's dictionary of attributes

dollar = base.__dict__["$"]
dollar(NY8, "AREANAME")



回答2:


Could not get the accepted answer to work so wrote this function:

def subset_RS4(rs4, subset):
    subset_func = r("""function(o, s){
    o[s]
    }
    """)
    return subset_func(rs4, subset)

Now you can call subset_RS4 with your object as the first arg and the subset as the other.

I am using it like this:

subset1 = r[">"](r["width"](peaks1), args.min_width)
print(subset_RS4(peaks1, subset1))


来源:https://stackoverflow.com/questions/29585543/how-to-extract-rs4-element-in-rpy2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!