从Rscript交互式地运行R

8
我正在尝试从一个R脚本启动一个shiny应用程序或交互式.Rmd文档。但是,我得到的只是一个信息:

Listening on http://127.0.0.1:...

我认为这是因为R正在运行交互模式(关于此的另一篇文章)。我该如何编写正确的R脚本,以便以下任何一个都可以工作?

我的脚本

#!/usr/bin/Rscript

## This
library(shiny)
runApp(appDir = "../app")

## Or this
## rmarkdown::run("Main.Rmd")
2个回答

5
如果我理解您的问题正确,我能够通过littler来实现这一点,而不是使用Rscript进行围绕R的脚本任务。我正在运行CentOS 7,根据您问题中的代码,看起来您正在使用类Unix的机器,因此安装littler应该不是问题。为了实现最小的可重复性,我使用了由RStudio提供的默认shiny应用程序和基于shiny的Rmarkdown模板,将它们分别保存为testapp(项目/应用程序目录名称)和testRMD.rmd。然后,我有以下脚本:


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"))

设置这些文件的权限以便它们可以被执行 -

[nathan@nrussell R]$ chmod +x testapp.r testRMD.r

(chmod +u ...应该足够了,但无论如何...), 然后您就可以从终端中运行它们了,等等...


[nathan@nrussell R]$ ./testapp.r
Loading required package: shiny

Listening on http://127.0.0.1:7088

enter image description here

[nathan@nrussell R]$ ./testRMD.r
Loading required package: shiny

Listening on http://127.0.0.1:7088

在此输入图像描述


有关Rmd文件的一些其他命令行输出被省略了,但是如果需要,这些输出很容易被抑制。总之,这似乎正常工作- shiny应用程序和Rmarkdown应用程序都是交互式的,就像从RStudio启动时一样- 但是如果您有其他想法,请澄清。


非常感谢!由于某些原因,我一直假设 launch.browser 值为真 (facepalm)。虽然我还没有尝试过 littler,但它看起来非常不错。现在我需要将它与 Windows 共享。在尝试时,我发现在渲染 RMarkdown 时,由于某种原因需要使用 default_file 而不是 file 指定文件名。 - Rorschach
@nongkrong 很好,希望这能有所帮助。我没有用Rscript进行过测试,但是它也应该可以使用;无论如何,我认为 launch.browser 参数是关键点。 - nrussell

0

感谢 @nrussell,你的示例对我帮助很大!

这是我在 Windows 10 上启动交互式 Markdown 文档的解决方案。

REM Change to correct directory
cd "C:\Users\me\Documents\project_folder\"

REM Print files available (not required, but helpful)
dir

REM Point system to R's Pandoc with Rscript then launch
"C:\Program Files\R\R-4.0.3\bin\Rscript.exe" -e ^
"Sys.setenv(RSTUDIO_PANDOC='C:/Users/me/Documents/RStudio/bin/pandoc'); rmarkdown::run(file = 'myInteractiveMarkdown.Rmd', shiny_args = list(launch.browser = TRUE, host = '127.0.0.1'))"

我最初发现了两个错误:

  1. 当我没有将系统环境指向R的pandoc时,它会给出错误消息error pandoc version 1.12.3 or higher is required,我使用这里中的说明解决了这个问题。
  2. 当我在shiny_args中设置端口时,后续执行bat文件时会出现端口已被占用的错误。

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