简体   繁体   English

运行涉及Python代码包的R脚本

[英]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. 所以我目前正在研究一个简单的python代码来运行一个简单的R脚本。 The R script is only about 6 lines but uses the package "pracma". R脚本只有大约6行,但使用“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' ". 在python中使用subprocesses模块,它运行脚本,但具有典型的“库中的错误(pracma):没有名为'pracma'的包”。 I am just looking for a simple solution to be able to run R scripts that have non-base packages installed. 我只是在寻找一个简单的解决方案,能够运行安装了非基础软件包的R脚本。 I know you can somehow do this using rpy2, but I cannot get that to install using pip, and I'm also using Anaconda3. 我知道你可以用rpy2以某种方式做到这一点,但我不能用pip来安装,我也在使用Anaconda3。

All in all, I'd just like a simple package that runs R scripts that have packages installed in them. 总而言之,我只是喜欢一个运行R脚本的简单包,其中安装了包。 Any help would be greatly appreciated. 任何帮助将不胜感激。

This is the relevant piece of my Python code: 这是我的Python代码的相关部分:

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: 这是我的R脚本:

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: 感谢@Dilettant:

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: 即使R看起来似乎没有这个单独运行脚本,当从python这样的东西运行R脚本时,我们需要确保脚本知道我们的库在哪个路径。这是通过在代码的开头添加这一行来实现的。 :

 .libPaths(dir\to\package)

If the code has any other lines involving changing working directory, those are unaffected by changing the library path. 如果代码具有涉及更改工作目录的任何其他行,则更改库路径不会影响这些行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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