【问题标题】:Run R interactively from Rscript从 Rscript 以交互方式运行 R
【发布时间】:2015-10-10 03:17:54
【问题描述】:

我正在尝试从 Rscript 启动闪亮的应用程序或交互式 .Rmd 文档。但是,我得到的只是一条消息

正在收听http://127.0.0.1:...

我相信这是因为 R 在交互模式下运行(another post 关于这个)。我怎样才能编写正确的 Rscript 以便以下任一项工作?

我的脚本

#!/usr/bin/Rscript

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

## Or this
## rmarkdown::run("Main.Rmd")

【问题讨论】:

    标签: r shiny r-markdown rscript


    【解决方案1】:

    如果我正确理解您的问题,我可以使用 littler 来实现这一点,我用它代替 Rscript 来编写围绕 R 的脚本任务。我正在运行 CentOS 7,并基于代码在您的问题中,您看起来像是在类似 Unix 的机器上,所以 installing littler 应该不是问题。为了最小化可重复性,我使用了 RStudio 提供的默认闪亮应用程序和基于闪亮的 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 文件的一些额外命令行输出,但我确信如果需要,可以轻松地抑制它。无论如何,这似乎工作正常 - 闪亮的应用程序和 Rmarkdown 应用程序都是交互式的,就像从 RStudio 启动时一样 - 但如果你有其他想法,请澄清。

    【讨论】:

    • 非常感谢!出于某种原因,我只是假设 launch.browser 总是正确的(facepalm)。我还没有尝试过小,但它看起来真的很好。不过,我现在也需要与 Windows 共享它。在尝试此操作时,我发现在渲染 rmarkdown 时,出于某种原因,我需要使用 default_file 而不是 file 指定文件名。
    • @nongkrong 太好了,HTH。我没有用 Rscript 对此进行测试,但它也应该适用于该接口;无论如何,我认为launch.browser 参数是这里的关键要点。
    【解决方案2】:

    感谢@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,我使用指令 here 解决了这个问题
    2. 当我在shiny_args中设置端口时,后续执行bat文件会得到端口已经忙的错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2012-02-28
      相关资源
      最近更新 更多