In my toy example, I am trying to render Rmd file in the shiny app while passing a variable from Shiny to Rmd. Somehow, the Rmd file is not able to pick the input input$selectInput passed to Rmd file. Can someone show me how to pass a variable from Shiny to Rmd file and print it there?
My intent is to use Rmd file as a template which will be filled by variables from Shiny App at runtime. There may be better alternatives to this approach to render HTML templates in Shiny, do let me know if you know any better approches.
library(shiny)
library(shinydashboard)
library(knitr)
sidebar <- dashboardSidebar(
collapsed = FALSE,
sidebarMenu(
id = "menu_sidebar",
conditionalPanel(
condition = "input.main_tab == 'tab 1'",
selectizeInput(inputId = "selectInput", label = "Choose an option", choices = c("a", "b", "c"), selected = "a", multiple = FALSE),
radioButtons(inputId = "buttons", label = "Choose one:",
choices=c(
"A" = "a",
"B" = "b"))
)
)
)
body <- dashboardBody(
fluidRow(
tabsetPanel(
id = "main_tab",
selected = "tab 1",
tabPanel(title = "tab 1", "Tab content 1",
conditionalPanel("input.buttons == 'a'",
{
knit("text1.Rmd", envir = globalenv(), quiet = T)
withMathJax(includeMarkdown("text1.md"))
},
tags$style("html, body {overflow: visible !important;")),
conditionalPanel("input.buttons == 'b'", htmlOutput("plot_overview_handler"))
)
)
)
)
shinyApp(
ui = dashboardPage(
dashboardHeader(title = "tabBoxes"),
sidebar,
body
),
server = function(input, output) {
output$tabset1Selected <- output$tabset2Selected <- renderText({
input$main_tab
})
output$plot_overview_handler <- renderUI({
pars <- list(variable_1 = input$selectInput)
includeMarkdown(rmarkdown::render(input = "text2.Rmd",
output_format = "html_document",
params = pars,
run_pandoc = FALSE,
quiet = TRUE,
envir = new.env(parent = globalenv())))
})
}
)
Rmd File 1 - text1.Rmd
---
title: "tst2"
output: html_document
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
#``` # Uncomment this to run code
## R Markdown
```{r cars}
print(input$selectInput)
#``` # Uncomment this to run code
Rmd File 2 - text2.Rmd
---
title: "tst2"
output: html_document
runtime: shiny
params:
variable_1: NA
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
#``` # Uncomment this to run code
## R Markdown
```{r cars}
print(params$variable_1)
#``` # Uncomment this to run code
Related
I am trying to adapt the RMarkdown file with *.rmd extension into Shiny application. My file has elements of Shiny but works with flexdashboard. Below you can see the code.
---
title: "Test"
author: " "
output:
flexdashboard::flex_dashboard:
orientation: columns
social: menu
source_code: embed
runtime: shiny
editor_options:
markdown:
wrap: 72
---
# Module 1
```{r global, include=FALSE}
library(biclust)
data(BicatYeast)
set.seed(1)
res <- biclust(BicatYeast, method=BCPlaid(), verbose=FALSE)
```
## Inputs {.sidebar}
```{r}
selectInput("clusterNum", label = h3("Cluster number"),
choices = list("1" = 1, "2" = 2),
selected = 1)
```
## Row {.tabset}
### Parallel Coordinates
```{r}
num <- reactive(as.integer(input$clusterNum))
renderPlot(
parallelCoordinates(BicatYeast, res, number=num()))
```
### Data for Selected Cluster
```{r}
renderTable(
BicatYeast[which(res#RowxNumber[, num()]), which(res#NumberxCol[num(), ])]
)
```
The shiny app usually has two main parts first is ui and second is server, so can anybody help how to solve this problem and run this file as a Shiny app.
library(shiny)
library(biclust)
ui <- fluidPage(
selectInput("clusterNum",
label = h3("Cluster number"),
choices = list("1" = 1, "2" = 2),
selected = 1
),
plotOutput("plot"),
tableOutput("table")
)
server <- function(input, output, session) {
set.seed(1)
data(BicatYeast)
res <- biclust(BicatYeast, method = BCPlaid(), verbose = FALSE)
num <- reactive(as.integer(input$clusterNum))
output$plot <-
renderPlot(
parallelCoordinates(BicatYeast, res, number = num())
)
output$table <-
renderTable(
BicatYeast[which(res#RowxNumber[, num()]), which(res#NumberxCol[num(), ])]
)
}
shinyApp(ui, server)
I am fairly new to R markdown. I have built an app that requires the user to provide multiple inputs to generate a table, which can then be saved locally.
I have been now asked to implement a sort of report to list all the variables inserted by the user (in a sort of formatted document), so that before generating the table one can review all the settings and change them in case of errors.
To avoid major UI restructure, I thought about using a r markdown document and visualize it inside a modal. My problem is that rmarkdown::render renders to an output, while bs_modal takes for the argument body a character (HTML) variable.
Is there a way to make this work? Or are there better way to accomplish this?
A minimal example:
my .Rmd
---
title: "Dynamic report"
output:
html_document: default
pdf_document: default
params:
n : NA
---
A plot of `r params$n` random points.
```{r, echo=FALSE}
plot(rnorm(params$n), rnorm(params$n))
```
My App.R
library(shiny)
library(bsplus)
library(rmarkdown)
shinyApp(
ui = fluidPage(
selectInput(
inputId = "numb",
label = "Label with modal help",
choices = 50:100
),
actionButton(inputId = "mysheet",
label = "Open modal") %>% bs_attach_modal(id_modal = "modal1"),
textOutput("result")
),
server = function(input, output) {
observeEvent(input$mysheet, {
params <- input$numb
md_out <-
rmarkdown::render(
"report.Rmd",
params = params,
envir = new.env(parent = globalenv())
)
bs_modal(
id = "modal1",
title = "Equations",
body = md_out,
size = "medium"
)
})
output$result <- renderText({
paste("You chose:", input$numb)
})
}
)
bs_modal does not work like this, it must be in the UI. Below is a solution using the classical Shiny modal, no bsplus or other package.
library(shiny)
shinyApp(
ui = fluidPage(
selectInput(
inputId = "numb",
label = "Label with modal help",
choices = 50:100
),
actionButton(inputId = "mysheet",
label = "Open modal"),
textOutput("result")
),
server = function(input, output) {
observeEvent(input$mysheet, {
params <- list(n = input$numb)
md_out <-
rmarkdown::render(
"report.Rmd",
params = params,
envir = new.env(parent = globalenv())
)
showModal(modalDialog(
includeHTML(md_out),
title = "Equations",
size = "m"
))
})
output$result <- renderText({
paste("You chose:", input$numb)
})
}
)
Use html_fragment as the Rmd output:
---
title: "Dynamic report"
output:
html_fragment
params:
n : NA
---
A plot of `r params$n` random points.
```{r, echo=FALSE}
plot(rnorm(params$n), rnorm(params$n))
```
I'm trying to make a reactive data table in R Shiny that has a button you can press to compile an RMarkdown document. Ultimately, I'm trying to combine the solutions from these two links:
R Shiny: Handle Action Buttons in Data Table and https://shiny.rstudio.com/articles/generating-reports.html. Here is what I have so far:
library(shiny)
library(shinyjs)
library(DT)
shinyApp(
ui <- fluidPage(
DT::dataTableOutput("data")
),
server <- function(input, output) {
useShinyjs()
shinyInput <- function(FUN, len, id, ...) {
inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))
}
inputs
}
df <- reactiveValues(data = data.frame(
Portfolio = c('Column1', 'Column2'),
Option_1 = shinyInput(downloadButton, 2, 'compile_', label = "Compile Document", onclick = 'Shiny.onInputChange(\"compile_document\", this.id)' ),
stringsAsFactors = FALSE,
row.names = 1:2
))
output$data <- DT::renderDataTable(
df$data, server = FALSE, escape = FALSE, selection = 'none', filter='top'
)
output$compile_document <- downloadHandler(
filename = "report.html",
content = function(file) {
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
params <- list(n = input$slider)
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
Here is the RMarkdown document I'd like to compile:
---
title: "Dynamic report"
output: html_document
params:
n: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `params$n` random points.
```{r}
plot(rnorm(params$n), rnorm(params$n))
```
The pieces all seem to be there, but I can't connect the "Compile Document" button to the download handler.
Here is a way that does not use downloadHandler.
library(shiny)
library(DT)
library(base64enc)
library(rmarkdown)
js <- '
Shiny.addCustomMessageHandler("download", function(b64){
const a = document.createElement("a");
document.body.append(a);
a.download = "report.docx";
a.href = b64;
a.click();
a.remove();
})
'
buttonHTML <- function(i){
as.character(
actionButton(
paste0("button_", i), label = "Report",
onclick = sprintf("Shiny.setInputValue('button', %d);", i)
)
)
}
dat <- data.frame(
PortFolio = c("Column 1", "Column 2")
)
dat$Action <- sapply(1:nrow(dat), buttonHTML)
ui <- fluidPage(
tags$head(tags$script(HTML(js))),
br(),
sliderInput("slider", "Sample size", min = 10, max = 50, value = 20),
br(),
DTOutput("dtable")
)
server <- function(input, output, session){
output[["dtable"]] <- renderDT({
datatable(dat, escape = -ncol(dat)-1)
})
observeEvent(input[["button"]], {
showNotification("Creating report...", type = "message")
tmpReport <- tempfile(fileext = ".Rmd")
file.copy("report.Rmd", tmpReport)
outfile <- file.path(tempdir(), "report.html")
render(tmpReport, output_file = outfile,
params = list(
data = dat[input[["button"]], -ncol(dat)],
n = input[["slider"]]
)
)
b64 <- dataURI(
file = outfile,
mime = "text/html"
)
session$sendCustomMessage("download", b64)
})
}
shinyApp(ui, server)
The rmd file:
---
title: "Dynamic report"
output: html_document
params:
data: "x"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Row contents:
```{r}
params$data
```
A plot of `params$n` random points:
```{r}
plot(rnorm(params$n), rnorm(params$n))
```
I'm trying to create an Rmarkdown that displays different amounts of text based on user input into a shiny application. I've made an basic example below. There are 2 text inputs and a checkbox. If the checkbox is false only the 1st text box value is printed to the markdown. If the checkbox is true then both values are printed. I want the output for both text boxes to appear like the 1st textbox output.
Ui:
library(shiny)
library(shinyjs)
ui <- fluidPage(
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
textInput(inputId = "text1",
label = "1st text", value = "1st text"),
checkboxInput(inputId = "checkBox", label = "Checkbox"),
textInput(inputId = "input2",
label = "2nd text", value = "2nd text"),
downloadButton("download", "Download button")
),
mainPanel(
verbatimTextOutput("checkBoxValue")
)
)
)
Server:
library(shiny)
library(shinyjs)
server <- function(input, output) {
output$checkBoxValue <- renderText(input$checkBox)
Text1Value <- reactive({input$text1})
BoxValue<- reactive(input$checkBox)
Input2Value <- reactive({input$input2})
output$download <- downloadHandler(
filename = "Test.docx",
content = function(file) {
tempReport <- file.path(tempdir(), "TestRMD.Rmd")
file.copy("TestRMD.Rmd", tempReport, overwrite = TRUE)
params = list(
Text1Value = Text1Value(),
BoxValue = BoxValue(),
Input2Value = Input2Value()
)
rmarkdown::render(
tempReport,
output_file = file,
params = params,
envir = new.env(parent = globalenv()),
quiet = FALSE
)
})
}
Rmarkdown:
---
title: "Test"
output: word_document
params:
Text1Value: NA
BoxValue: NA
Input2Value: NA
---
```{r echo= FALSE, message = FALSE, include = FALSE}
library(shiny)
library(knitr)
library(latex2exp)
Text1Value<- params$Text1Value
BoxValue<- params$BoxValue
Input2Value<- params$Input2Value
```
# Value for text 1 is `r Text1Value`
```{r, echo=FALSE}
if(BoxValue == TRUE){
"Value for input 2 is `r Input2Value`"
}
```
Currently I can get the text from the second text output to appear conditionally, however it renders looking like R code. I want it to appear in the same format as the output for the 1st text input.
How would I accomplish this?
The the following in your Rmd file. You already are in a code block and don't need to have additional inline r formatting. You can use results = 'asis' in your block and also add the header (#) for identical formatting if you'd like:
```{r, echo=FALSE, results='asis'}
if(BoxValue == TRUE){
cat("# Value for input 2 is", Input2Value)
}
```
I have a tough time to figure out how i can use if statement inside the .Rmd file or so. I could not find anything on stackoverflow...
I am going explain on the example of this shiny app:
library(shiny)
library(markdown)
library(knitr)
server <- function(input, output) {
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
out <- rmarkdown::render('report.Rmd',
params = list(text = input$text),
switch(input$format,
PDF = pdf_document(),
HTML = html_document(),
Word = word_document()
))
file.rename(out, file)
}
)
}
ui <- fluidPage(
tags$textarea(id="text", rows=20, cols=155,
placeholder="Some placeholder text"),
tabPanel("Data",
radioButtons('filter', h3(strong("Auswahlkriterien:")),
choices = list("WerkstoffNr" = 1,
"S-Gehalt" = 2),
selected = 1,inline=TRUE),
conditionalPanel(
condition = "input.filter == '1'",
column(6,
h4("WerkstoffNr auswaehlen:"),
selectInput("select", " ",
choices = seq(1,100,10))),
column(6,
h4("Abmessung auswaehlen:"),
selectInput("abmfrom", "Von:",choices=as.list(seq(20,110,10))),
selectInput("abmto", "Bis:",choices=as.list(seq(20,110,10))),
actionButton("button1", "Auswaehlen"))),
conditionalPanel(
condition = "input.filter == '2' ",
column(6,h4("S-Gehalt auswaehlen:"),
selectInput("sgehalt", "Von:",choices=seq(1,100,10)),
selectInput("sgehalt2", "Bis:",choices=seq(1,100,10))),
column(6,h4("Abmessung auswaehlen:"),
selectInput("abmfrom2", "Von:",choices=as.list(seq(20,110,10))),
selectInput("abmto2", "Bis:",choices=as.list(seq(20,110,10)))))
),
flowLayout(radioButtons('format', 'Document format', c('PDF','HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'))
)
shinyApp(ui = ui, server = server)
report.Rmd (it is just this at the moment):
---
title: "Parameterized Report for Shiny"
output: html_document
params:
text: 'NULL'
---
# Some title
`r params[["text"]]`
I would like to inside of my RMarkdown Report to have the input from this part of shiny app:
tabPanel("Data",
radioButtons('filter', h3(strong("Auswahlkriterien:")),
choices = list("WerkstoffNr" = 1,
"S-Gehalt" = 2),
selected = 1,inline=TRUE),
conditionalPanel(
condition = "input.filter == '1'",
column(6,
h4("WerkstoffNr auswaehlen:"),
selectInput("select", " ",
choices = seq(1,100,10))),
column(6,
h4("Abmessung auswaehlen:"),
selectInput("abmfrom", "Von:",choices=as.list(seq(20,110,10))),
selectInput("abmto", "Bis:",choices=as.list(seq(20,110,10))),
actionButton("button1", "Auswaehlen"))),
conditionalPanel(
condition = "input.filter == '2' ",
column(6,h4("S-Gehalt auswaehlen:"),
selectInput("sgehalt", "Von:",choices=seq(1,100,10)),
selectInput("sgehalt2", "Bis:",choices=seq(1,100,10))),
column(6,h4("Abmessung auswaehlen:"),
selectInput("abmfrom2", "Von:",choices=as.list(seq(20,110,10))),
selectInput("abmto2", "Bis:",choices=as.list(seq(20,110,10)))))
)
As we can see there is an If statement inside (concerning filtering option). So it depends on the user which option would like to use to filter the data. I would like to have this option inside of my Report. Just smthg easily like:
if input.filter == 1
Werkstoffnummer: input$select
Abmessung: von input$abmfrom bis input$abmto
else
S : von sgehalt bis sgehalt2
Abmessung: von input$abmfrom2 bis input$abmto2
So in the report will be only printed (if input.filter ==1):
Werkstoffnummer: 1
Abmessung: von 20 bis 30
Thanks so much!
May be I not fully understand you but you can use something like
(example print different text insist on input filter)
---
title: "Untitled"
runtime: shiny
output: html_document
---
```{r eruptions, echo=FALSE}
radioButtons('filter', h3(strong("Auswahlkriterien:")),
choices = list("WerkstoffNr" = 1,
"S-Gehalt" = 2),
selected = 1,inline=TRUE)
conditionalPanel(
condition = "input.filter == '1'",
column(6,
h4("WerkstoffNr auswaehlen:")
))
conditionalPanel(
condition = "input.filter == '2' ",
column(6,h4("S-Gehalt auswaehlen:")))
```
Or use server side ( render UI , like here )
but you cant shared it like static html file :
*"Note: If you are familiar with R Markdown, you might expect RStudio to save an HTML version of an interactive document in your working directory. However, this only works with static HTML documents. Each interactive document must be served by a computer that manages the document. As a result, interactive documents cannot be shared as a standalone HTML file."
Update
If you want download static html
example
report.rmd
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r ,echo=FALSE}
if(input$filter==1){
h1(paste("1",input$ii))
}else{
h1(paste("2",input$ii))
}
```
Shiny
library(shiny)
ui=shinyUI(fluidPage(
radioButtons('filter', h3(strong("Auswahlkriterien:")),
choices = list("WerkstoffNr" = 1,
"S-Gehalt" = 2),
selected = 1,inline=TRUE),
numericInput("ii","1",0),
downloadButton('downloadReport')
))
server=shinyServer(function(input, output) {
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', 'html' )
},
content = function(file) {
src <- normalizePath('report.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, 'report.Rmd')
library(rmarkdown)
out <- render('report.Rmd', html_document())
file.rename(out, file)
}
)
})
shinyApp(ui,server )
Report will contain 1 or 2 insist on radio button and ii input
It sounds like what you want is a template to generate the report. R Markdown is a format for pretty-printing reports rather than generating them.
For report generation, there’s ‹brew›. It lets you generate any file (including R Markdown) using a simple template language. In your case, you could do something like:
<% if (input.filter == 1) { %>
… normal R Markdown code here!
<% } %>
Save this as report.rmd.brew or similar; then, in your report generation code, you need to brew the template before rendering it:
brew::brew('report.rmd.brew', 'report.rmd')
It finds the variables from the current environment by default (this can be configured).