简体   繁体   中英

Running an R script that involves Packages from Python Code

So I'm currently working on a simple python code to run a simple R script. The R script is only about 6 lines but uses the package "pracma". Using the subprocesses module in python, It runs the script but with the typical "Error in library(pracma) : there is no package called 'pracma' ". I am just looking for a simple solution to be able to run R scripts that have non-base packages installed. I know you can somehow do this using rpy2, but I cannot get that to install using pip, and I'm also using Anaconda3.

All in all, I'd just like a simple package that runs R scripts that have packages installed in them. Any help would be greatly appreciated.

This is the relevant piece of my Python code:

sp.run('Rscript Hausdorff.R', shell=True)

bFile = open("HausdorffData/hausdorff.txt", "r")
result = bFile.read()
bFile.close()
hausdorff_dist = float(result)

return hausdorff_dist

This is my R script:

library(pracma)

setwd('HausdorffData')

PointsA <- as.matrix(read.table("HFileA.txt", header = FALSE))
PointsB <- as.matrix(read.table("HFileB.txt", header = FALSE))

H = hausdorff_dist(PointsA, PointsB)
write(H, file = "hausdorff.txt",ncolumns = 1, append = FALSE)

This produces the following error:

Error in library(pracma) : there is no package called 'pracma'
Execution halted

Thanks to @Dilettant for this:

Even when R can seemingly run the script individually without this, when running the R script from something like python, we need to make sure the script knows what path our library is in. This is achieved by adding this line to the start of the code:

 .libPaths(dir\to\package)

If the code has any other lines involving changing working directory, those are unaffected by changing the library path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM