从 Windows 命令提示符运行 R

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5720317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:18:39  来源:igfitidea点击:

running R from windows command prompt

windowsrplatform

提问by babu

I have a R program in a txt file say "functions.txt".
I load the "functions.txt"file the R using source("function.txt")and then call functions f1(), f2()etc. which are declared and defined within "function.txt"file.
I also need to load a couple of R libraries using library()before I can use f1(), f2()etc.

我在 txt 文件中有一个 R 程序说"functions.txt"
我加载"functions.txt"使用文件将R source("function.txt"),然后调用函数f1()f2()等,其被声明和内定义 "function.txt"文件。
我还需要在使用library()之前加载几个 R 库f1()f2()等等。

My question is can I acheive all this (i.e. calling function f1()and f2()) from the windows prompt without opening the R environment ?

我的问题是我可以在不打开 R 环境的情况下从 Windows 提示中实现所有这些(即调用函数f1()f2())吗?

So essentially I want to

所以基本上我想

  1. load the R libraries I need to run f1(), f2()etc.
  2. load the function.txtfile
  3. run the individual functions f1() etc.
  4. record the result
  1. 加载将R库我需要运行f1()f2()等等。
  2. 加载function.txt文件
  3. 运行单个函数 f1() 等。
  4. 记录结果

all from from the command promt of windows c:\>

全部来自 Windows 的命令提示符 c:\>

I have windows version of R installed in my computers.
It would be very kind of anyone to give a detailed answer as I am not very computer savvy.

我的计算机上安装了 Windows 版本的 R。
任何人都可以给出详细的答案,因为我不是很精通计算机。

Regards

问候

回答by Dirk Eddelbuettel

Bart's post is correct, but this can be done simpler. If the code

Bart 的帖子是正确的,但这可以更简单地完成。如果代码

f1 <- function() {
  print("A")
}

f2 <- function() {
  print("B")
}

f1()
f2()

is in a file 'myRcode.R'; then

在文件“myRcode.R”中;然后

Rscript myRcode.R

will load and execute it, including the two function calls.

将加载并执行它,包括两个函数调用。

Rscript.exeis in the same directory as R.exe-- which one may have to add to the $PATH.

Rscript.exeR.exe-位于同一目录中- 可能必须将其添加到$PATH.

回答by Bart Kiers

The following "works on my machine" (not Windows though, but it should...):

以下“适用于我的机器”(虽然不是 Windows,但它应该......):

If your functions.txtlooks like:

如果你functions.txt看起来像:

f1 <- function()
{
  print("A")
}

f2 <- function()
{
  print("B")
}

the command:

命令:

Rscript -e "source('functions.txt');f1();f2()" > out.txt

should create the file out.txtcontaining:

应该创建out.txt包含以下内容的文件:

[1] "A"
[1] "B"

回答by Bill Yarberry

Here's a command line script, based on code above:

这是一个命令行脚本,基于上面的代码:

d:\misc2\bin\Rscript.exe    d:\r_code\mycode.r

Using Windows 7, I ran it as a .bat file. Works fine. Thanks for the tip. (of course, these are just my particular subdirectories)

使用 Windows 7,我将它作为 .bat 文件运行。工作正常。谢谢你的提示。(当然,这些只是我的特定子目录)