从 python 运行 R 脚本 [英] Running R script from python
问题描述
我搜索了这个问题并找到了一些答案,但它们似乎都不起作用.这是我在 python 中使用的脚本来运行我的 R 脚本.
I searched for this question and found some answers on this, but none of them seem to work. This is the script that I'm using in python to run my R script.
import subprocess
retcode = subprocess.call("/usr/bin/Rscript --vanilla -e 'source(\"/pathto/MyrScript.r\")'", shell=True)
我收到此错误:
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
no lines available in input
Calls: source ... withVisible -> eval -> eval -> read.csv -> read.table
Execution halted
这是我的 R 脚本的内容(非常简单!)
and here is the content of my R script (pretty simple!)
data = read.csv('features.csv')
data1 = read.csv("BagofWords.csv")
merged = merge(data,data1)
write.table(merged, "merged.csv",quote=FALSE,sep=",",row.names=FALSE)
for (i in 1:length(merged$fileName))
{
fileConn<-file(paste("output/",toString(merged$fileName[i]),".txt",sep=""))
writeLines((toString(merged$BagofWord[i])),fileConn)
close(fileConn)
}
当我在 r 命令行中使用 source('MyrScript.r')
时,r 脚本工作正常.此外,当我尝试使用我传递给 subprocess.call
函数的确切命令(即 /usr/bin/Rscript --vanilla -e 'source("/pathto/MyrScript.r")'
) 在我的命令行中可以找到,我真的不明白有什么问题.
The r script is working fine, when I use source('MyrScript.r')
in r commandline. Moreover, when I try to use the exact command which I pass to the subprocess.call
function (i.e., /usr/bin/Rscript --vanilla -e 'source("/pathto/MyrScript.r")'
) in my commandline it works find, I don't really get what's the problem.
推荐答案
我不会太相信 Rscript
调用中的 source 因为你可能不完全理解在哪里您是否正在运行不同的嵌套 R 会话.该过程可能会因为一些简单的事情而失败,例如您的工作目录不是您所想的那样.
I would not trust too much the source within the Rscript
call as you may not completely understand where are you running your different nested R sessions. The process may fail because of simple things such as your working directory not being the one you think.
Rscript
允许您直接运行脚本(如果您使用的是 Linux,请参阅 man Rscript
).
Rscript
lets you directly run an script (see man Rscript
if you are using Linux).
那你可以直接做:
subprocess.call ("/usr/bin/Rscript --vanilla /pathto/MyrScript.r", shell=True)
或者更好地将 Rscript
命令及其参数解析为列表
or better parsing the Rscript
command and its parameters as a list
subprocess.call (["/usr/bin/Rscript", "--vanilla", "/pathto/MyrScript.r"])
此外,为了简化操作,您可以创建一个 R 可执行文件.为此,您只需将其添加到脚本的第一行:
Also, to make things easier you could create an R executable file. For this you just need to add this in the first line of the script:
#! /usr/bin/Rscript
并赋予它执行权.请参阅此处细节.
and give it execution rights. See here for detalis.
然后你就可以像调用任何其他 shell 命令或脚本一样执行你的 python 调用:
Then you can just do your python call as if it was any other shell command or script:
subprocess.call ("/pathto/MyrScript.r")
这篇关于从 python 运行 R 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!