我正在尝试使用
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 时——我认为你有两个选择:
- 使用
readLines(con = "stdin", n = 1)
从终端读取用户输入。 - 改为调用脚本时,使用
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!
关于r - 如何在命令提示符下获取用户输入并将其传递给 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70521543/