从Rscript交互运行R
从Rscript交互运行R
我正在尝试从Rscript启动一个闪亮的应用程序或交互式的.Rmd文档。 但是,我得到的只是一个消息
在http://127.0.0.1上监听:...
我认为这是因为R正在交互模式下运行(另一篇帖子关于此)。 我该如何编写正确的Rscript,以便以下任何一个都可以工作?
我的脚本
#!/usr/bin/Rscript ## This library(shiny) runApp(appDir = "../app") ## Or this ## rmarkdown::run("Main.Rmd")
admin 更改状态以发布 2023年5月24日
感谢 @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'))"
我最初发现了两个错误:
- 当我没有将系统环境指向 R 的 pandoc 时,它会给出错误消息
error pandoc version 1.12.3 or higher is required
,我通过这里的说明解决了这个问题。 - 当我在
shiny_args
中设置端口时,批处理文件的后续执行会出现端口已被占用的错误。
如果我理解你的问题正确,我可以用 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
[nathan@nrussell R]$ ./testRMD.r Loading required package: shiny Listening on http://127.0.0.1:7088
有一些额外的命令行输出用于Rmd
文件,我省略了它们,但如果需要,它们可以很容易地被抑制。总之,这似乎正常工作 - shiny应用程序和Rmarkdown应用程序都是互动的,就像从RStudio启动一样 - 但是如果你有其他的想法,请澄清。