python - Getting Rpy2 to work with rgdal to spatially subset points -
so have r code works. takes bunch of points data , spatially subsets against shapefile in method of http://robinlovelace.net/r/2014/07/29/clipping-with-r.html.
#data .csv file lon lat points data_points <- spatialpoints(data) proj4string(data_points) <- crs("+proj=longlat +datum=wgs84 +no_defs +ellps=wgs84 +towgs84=0,0,0") data_ll <- sptransform(data_points, crs("+proj=longlat +datum=wgs84 +no_defs +ellps=wgs84 +towgs84=0,0,0")) melbourne <- readogr("melbourne_australia.land.coastline","melbourne_australia_land_coast") #this shapefile https://mapzen.com/data/metro-extracts subset <- data_ll[melbourne,]
plot(melbourne) points(subset)
i'm trying convert corresponding rpy2 script. far have;
import pandas pd import numpy np import rpy2.robjects ro import rpy2.robjects.numpy2ri rpy2.robjects.packages import importr rgdal = importr('rgdal') base = importr('base') rpy2.robjects.numpy2ri.activate() data = pd.read_csv('sim.csv') data = data.values coordinates = ro.r['coordinates'] proj4string = ro.r['proj4string'] sptransform = ro.r['sptransform'] readogr = ro.r['readogr'] spatialpoints = ro.r['spatialpoints'] crs = ro.r['crs'] class_r = ro.r['class'] key = crs("+proj=longlat +datum=wgs84 +no_defs +ellps=wgs84 +towgs84=0,0,0") data_points = spatialpoints(data, proj4string = key) data_ll = sptransform(data_points, key) melbourne = readogr("melbourne_australia.land.coastline", "melbourne_australia_land_coast") subset = data_ll[melbourne,]
which fails on last line error typeerror: 'rs4' object not subscriptable. have idea of going on?
one way convert r code function , import package.
this r code:
library(rgdal) library(sp) #import data data <- read.csv("sim.csv", header = f) subset_points <- function(data){ data_points <- spatialpoints(data, proj4string=crs("+proj=longlat +datum=wgs84 +no_defs +ellps=wgs84 +towgs84=0,0,0")) data_ll <- sptransform(data_points, crs("+proj=longlat +datum=wgs84 +no_defs +ellps=wgs84 +towgs84=0,0,0")) sink("/dev/null") melbourne <- readogr("melbourne_australia.land.coastline", "melbourne_australia_land_coast") sink() subset <- data_ll[melbourne,] final <- as.data.frame(subset) return(final) }
and python code:
import rpy2.robjects ro import rpy2.robjects.numpy2ri rpy2.robjects.packages import importr rpy2.robjects.packages import signaturetranslatedanonymouspackage open('subset_data.r') fh: rcode = os.linesep.join(fh.readlines()) subset = signaturetranslatedanonymouspackage(rcode, "subset") rpy2.robjects.numpy2ri.activate() data = pd.read_csv('sim.csv') data = data.values final = subset.subset_points(data) print(np.array(final).t)
Comments
Post a Comment