使用Python执行.R脚本

3

经过七个小时的谷歌搜索和阅读类似问题的内容,以及大量的试错,我现在可以放心地寻求一些指导。

为了简化我的实际任务,我创建了一个非常基本的R脚本(命名为test_script):

x <- c(1,2,3,4,5)
avg <- mean(x)
write.csv(avg, file = "output.csv")

这个如预期一样工作。

我是Python的新手,正在尝试弄清楚如何执行R脚本,以便创建相同的.csv文件。

不错的结果来自于:

subprocess.call(["C:/Program Files/R/R-2.15.2/bin/R", 'C:/Users/matt/Desktop/test_script.R'])

这将打开一个带有典型 R 启动文本的 cmd 窗口,但是会有一条消息:ARGUMENT 'C:/Users/matt/Desktop/test_script.R' __ ignored __(参数'C:/Users/matt/Desktop/test_script.R'被忽略)。

另外:

subprocess.call(['C:/Program Files/R/R-2.15.2/bin/Rscript', 'C:/Users/matt/Desktop/test_script.r'])

这会弹出一个命令行窗口并返回0,但没有创建任何.csv文件。
否则,我已经尝试了在这个网站或其他任何地方找到的所有建议。非常感谢您的时间和努力。

1
我有点困惑。你还没有发现rpy吗? - joran
1
当然。我已经研究了Rpy并安装了它的后继者Rpy2。然而,我需要在R中完成的所有工作都已经完成,我只是想执行脚本。如果有一种方法可以在Rpy2中实现这一点,那么我非常乐意听取建议! - Mryan_Pledge
2个回答

3

在命令提示符下运行R --help将打印:

Usage: R [options] [< infile] [> outfile]
   or: R CMD command [arguments]

Start R, a system for statistical computation and graphics, with the
specified options, or invoke an R tool via the 'R CMD' interface.

Options:
  -h, --help            Print short help message and exit
  --version             Print version info and exit
  ...
  -f FILE, --file=FILE  Take input from 'FILE'
  -e EXPR               Execute 'EXPR' and exit

FILE may contain spaces but not shell metacharacers.

Commands:
  BATCH         Run R in batch mode
  COMPILE       Compile files for use with R
  ...

尝试

call(["C:/Program Files/R/R-2.15.2/bin/R", '-f', 'C:/Users/matt/Desktop/test_script.R'])

还有一些其他的命令行参数可以传递给R,可能会有所帮助。运行R --help以查看完整列表。


1
大多数人更喜欢使用Rscript进行批处理式执行。 - Dirk Eddelbuettel

1

也许现在已经晚了,但希望能对其他人有所帮助:

只需在调用列表中添加--vanilla即可。

subprocess.call(['C:/Program Files/R/R-2.15.2/bin/Rscript',  '--vanilla', 'C:/Users/matt/Desktop/test_script.r'])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接