从 Rscript 以交互方式运行 R [英] Run R interactively from Rscript
问题描述
我正在尝试从 Rscript 启动一个闪亮的应用程序或交互式 .Rmd 文档.然而,我得到的只是一条消息
I'm trying to start a shiny app or an interactive .Rmd document from an Rscript. However, all I get is a message
正在收听 http://127.0.0.1:...
我相信这是因为 R 以交互模式运行(另一个发布关于这个).我如何编写正确的 Rscript 以便以下任一方法都可以工作?
I believe this is because R is running in interactive mode (another post about this). How can I write the proper Rscript so that either of the following would work?
#!/usr/bin/Rscript
## This
library(shiny)
runApp(appDir = "../app")
## Or this
## rmarkdown::run("Main.Rmd")
推荐答案
如果我正确理解您的问题,我能够通过 littler,我用它代替 Rscript
来编写围绕 R 的脚本任务.我正在运行 CentOS 7,并基于您的代码问题看起来你在一个类 Unix 的机器上,所以 安装 littler 应该不是问题.为了最小的可重复性,我使用了 RStudio 提供的默认闪亮应用程序和基于闪亮的 Rmarkdown 模板,将它们保存为 testapp
(项目/应用程序目录名称)和 testRMD.rmd
, 分别.然后,我有以下脚本:
If I understand your question correctly, I was able to achieve this with littler, which I use in lieu of Rscript
for scripting tasks that revolve around R. I'm running CentOS 7, and based on the code in your question it looks like you are on a Unix-like machine, so installing littler should not be an issue. For minimal reproducibility, I used the default shiny application and shiny-based Rmarkdown templates provided by RStudio, saving them as testapp
(the project / application directory name) and testRMD.rmd
, respectively. Then, I have the following scripts:
testapp.r
#!/usr/bin/env r
shiny::runApp(
"~/tmp/delete/testapp",
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1")
<小时>
testRMD.r
#!/usr/bin/env r
rmarkdown::run(
file = "testRMD.rmd",
dir = "~/tmp/delete",
shiny_args = list(
port = 7088,
launch.browser = TRUE,
host = "127.0.0.1"))
<小时>
为这些文件设置权限,以便它们可以执行 -
Set the permissions for these files so they can be executed -
[nathan@nrussell R]$ chmod +x testapp.r testRMD.r
(chmod +u ...
应该足够了,但无论如何...),你应该准备好从你的终端等运行它们......
(chmod +u ...
should suffice, but regardless...), and you should be all set to run them from your terminal, etc...
[nathan@nrussell R]$ ./testapp.r
Loading required package: shiny
Listening on http://127.0.0.1:7088
[nathan@nrussell R]$ ./testRMD.r
Loading required package: shiny
Listening on http://127.0.0.1:7088
我省略了 Rmd
文件的一些额外命令行输出,但我确信如果需要,这可以很容易地被抑制.无论如何,这似乎工作正常 - 闪亮的应用程序和 Rmarkdown 应用程序都是交互式的,就像从 RStudio 启动时一样 - 但如果您有其他想法,请澄清.
There is some additional command line output for the Rmd
file that I omitted, but I'm sure this could be suppressed easily if desired. Anyhow, this seems to be working properly - both the shiny application and Rmarkdown application are interactive, just as when launched from RStudio - but if you had something else in mind please clarify.
这篇关于从 Rscript 以交互方式运行 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!