如何在命令提示符下获取用户输入并将其传递给 R

How to get a user input in command prompt and pass it to R

我正在尝试使用

var <- as.numeric(readline(prompt="Enter a number: "))

稍后在计算中使用它。

在 RStudio 中 运行 时它工作正常,但我需要能够从 Windows 10 中的命令行传递此输入 我正在使用单行批处理文件

Rscript.exe "C:\My Files\R_scripts\my_script.R"

当它到达用户输入部分时,它会冻结并且不会提供预期的输出。

来自 readline() 的文档:

This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".

对于非交互式使用——从命令行调用 R 时——我认为你有两个选择:

  1. 使用readLines(con = "stdin", n = 1)从终端读取用户输入。
  2. 改为调用脚本时,使用 commandArgs(trailingOnly = TRUE) 从命令行提供输入作为参数。

下面是更多信息。

1。使用 readLines()

readLines() 看起来与您正在使用的 readline() 非常相似,但旨在逐行读取文件。如果我们不是将文件指向标准输入 (con = "stdin"),它将从终端读取用户输入。我们设置 n = 1 以便它在您按 Enter 时停止从命令行读取(也就是说,它只读取 一个 行)。

例子

在 R 脚本中使用 readLines()

# some-r-file.R

# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)

writeLines(args[[1]], "output.txt")

调用脚本:

Rscript.exe "some-r-file.R"

它现在会询问您的意见。这是 PowerShell 的屏幕截图,我在其中提供了“任何文本!”。

那么 output.txt 将包含:

Any text!

2。使用commandArgs()

从终端调用 Rscript.exe 时,您可以添加额外的参数。使用 commandArgs() 您可以捕获这些参数并在您的代码中使用它们。

示例:

在 R 脚本中使用 commandArgs()

# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)

writeLines(args[[1]], "output.txt")

调用脚本:

Rscript.exe "some-r-file.R" "Any text!"

那么 output.txt 将包含:

Any text!