Run R script from Python

I want to run an R-script from a Python script. An R-script is required to project the coordinates of a laton in another coordinate system. I examined two options for this. In the first version, I like to analyze the lat and lon coordinates in an R-script, which is shown below. Then, finally, I would like the R-script to return x and y back to the python script, but I cannot figure out how to do this.

project<-function(lat,lon){ library(sp) library(rgdal) xy <- cbind(x = lon, y = lat) S <- SpatialPoints(xy) proj4string(S) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") Snew <- spTransform(S, CRS("+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs")) x <- coordinates(Snew)[1] y <- coordinates(Snew)[2] return(x,y) } 

For my second option, I considered using an R-script at the bottom with lat and lon already in it. I am trying to run this from python using subprocess.Popen ('Rscript project.r', shell = True) .wait () But this does not work. He does not write the xy.txt file. However, if I run this from the cmd line, the R-script does the job. Who can help me with one of these two options?

 library(sp) library(rgdal) lat <- 52.29999924 lon <- 4.76999998 xy <- cbind(x = lon, y = lat) S <- SpatialPoints(xy) proj4string(S) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") Snew <- spTransform(S, CRS("+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs")) x <- coordinates(Snew)[1] y <- coordinates(Snew)[2] cat(x, file="xy.txt",sep="") cat(y,file="xy.txt",append=TRUE) 
+4
source share
2 answers

For your first solution - get R to print the coordinates to the console (using print or cat or something else in R), and then grab it in Python (see here running the shell command from Python and grabbing the output )

This will give you a string with lat / lon coordinates in it, you just need to parse them using suitable Python functions.

0
source

It seems to me that you are almost there, some comments:

  • x <- coordinates(Snew)[1] selects the first element, use x <- coordinates(Snew)[,1] to get the whole vector. This assumes that you are passing lat and lon vectors, not single values. There is no reason why we should not skip lat lon vectors.

  • return(x,y) invalid, R does not support the return of multiple objects. Instead, just return(cbind(x,y)) .

  • Inside the function, I would use require .

Regarding running code from Python, I would look at Rpy . This allows you to call R code from Python. Rpy does a lot of the hard work of passing R objects back and forth, so this is a good option in this case.

The approach that I would use in Rpy is to put project in a .R file, source this file and call project .

+1
source

Source: https://habr.com/ru/post/1479793/


All Articles