【问题标题】:rmarkdown shiny user input in chunk?rmarkdown闪亮的用户输入块?
【发布时间】:2016-03-26 08:26:03
【问题描述】:

我有一个闪亮的应用程序,它允许用户下载一个 HTML 文件(从 .Rmd 文件编写),其中包含用于根据所有用户输入运行分析的代码。我正在尝试编写当用户输入发生变化时会更改的基本 .Rmd 文件。我无法将用户输入变量(例如 input$button1)包含到 R 代码块中。说出 input$button1 = "text1" 的用户输入。

```{r} results <- someFun(input$button1) ```

我想把它织成这样:

```{r} results <- someFun('text1') ```

不过,每次我下载针织 HTML 时,我都会收到 input$button1 被写入文件。我还希望能够生成一个使用此替换格式化的 .Rmd 文件。似乎knit_expand() 可能是关键,但我似乎无法将可用示例与我的具体问题联系起来。 knit_expand() 整个 .Rmd 文件并明确指定要替换的所有参数的正确方法是,还是在 .Rmd 文件本身中有更优雅的方法?我更喜欢类似于this 的方法,除了不使用asis 引擎,我可以使用r 引擎。任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 重点是将其写入 HTML。
  • echo = FALSE 在输出中隐藏了 R 代码,还是我在这里遗漏了什么?
  • 这不是你想要的吗?试试echo=F, results='asis'
  • 不,我想显示代码,如我上面的示例所示。我希望用户输入显示为输入的任何内容。
  • 请粘贴您的整个 R 代码块。

标签: r shiny r-markdown


【解决方案1】:

知道了。下面的解决方案。感谢一辉的指导。诀窍是knit_expand() 整个.Rmd 文件,然后writeLines() 到一个新文件,然后渲染。事后看来,整个过程是有道理的。事后诸葛亮。

例如,p1 是字符参数 'ice cream',p2 是整数参数 10。在ui.R 中有一个用户定义的参数,名为input$mdType,用于决定提供下载的格式。

Rmd 文件:

Some other text.
```{r}
results <- someFun("{{p1}}", {{p2}})
``` 

在 server.R 内的downloadHandler() 中:

  content = function(file) {
    src <- normalizePath('userReport.Rmd')
    # temporarily switch to the temp dir, in case you do not have write
    # permission to the current working directory
    owd <- setwd(tempdir())
    on.exit(setwd(owd))
    file.copy(src, 'userReport.Rmd')
    exp <- knit_expand('userReport.Rmd', p1=input$p1, p2=input$p2)
    writeLines(exp, 'userReport2.Rmd')

    out <- rmarkdown::render('userReport2.Rmd', switch(input$mdType, 
             PDF = pdf_document(), HTML = html_document(), Word = word_document()))
    }
    file.rename(out, file)
  }

渲染前生成的 userReport2.Rmd:

```{r}
results <- someFun("ice cream", 10)
```

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 2017-03-03
    • 2018-04-17
    • 1970-01-01
    • 2017-03-08
    • 2020-04-14
    • 2023-04-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多