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).
Related
I made an R script that allows to get an R Markdown report with a certain type of dataset. Now I would like other people to be able to use this script in order to get an automated report with their data but without using this script (especially for people who don't master R).
I try to go through Shiny hoping to make an interface that loads a dataset and would make my script automatically but I can't make the link between Shiny and my Rmd.
How can I tell my Rmd that the dataset to be processed is not the one that my Rmd script was going to look for in a directory but the one that was loaded on the Shiny interface?
Thanks
Here is the Shiny script with my Rmd called "traitemant_bis.Rmd" :
library(shiny)
library(rmarkdown)
ui <- fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "file1", label = "Choose CSV File",
multiple = FALSE,
accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")
),
radioButtons("format", "Document format", c("PDF", "HTML", "Word"), inline = TRUE)
),
mainPanel(
tableOutput("contents"),
downloadButton("downloadReport")
)
)
)
server <- function(input, output) {
dataset <- reactive({
req(input$file1)
read.csv(file = input$file1$datapath,
na.strings = ".",
sep = ";",
header = TRUE,
nrows=10)
})
output$contents <- renderTable({
req(dataset())
head(dataset())
})
output$downloadReport <- downloadHandler(
filename = function() {
paste("my-report", sep = ".", switch(
input$format, PDF = "pdf", HTML = "html", Word = "docx"
))
},
content = function(file) {
src <- normalizePath("traitemant_bis.Rmd")
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, "traitemant_bis.Rmd", overwrite = TRUE)
out <- render("traitemant_bis.Rmd", switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui, server) ```
I'm giving a simple example showing how you can achieve this. Basically, you can pass any of your data from shiny to Rmd as params.
If you have multiple data frames or any data convert them to a single list and pass as params, you can extract individual data later in the RMarkdown
app.R
library(shiny)
ui <- fluidPage(
# Application title
titlePanel("RMD example"),
downloadButton("btn", "Generate Report")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
data <- reactive({
mtcars
})
output$btn <- downloadHandler(
filename = function(){"myreport.docx"},
content = function(file) {
tempReport <- file.path(tempdir(),"markdown.Rmd")
file.copy("markdown.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render("markdown.Rmd", output_format = "word_document", output_file = file,
params = list(table = data()), # here I'm passing data in params
envir = new.env(parent = globalenv()),clean=F,encoding="utf-8"
)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
Rmd file
---
title: "Untitled"
author: "Mohan"
date: "2/17/2021"
params:
table: [some object]
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
params$table -> data
data
summary(data)
```
I need to print a report from a shiny application using r markdown. I have been trying to follow the examples, but after many hours, I need some help.
There are 4 files: app.R, report.Rmd, calculations.R and datos.xlsx
datos.xlsx is an excel file with information to be used by a function defined in calculations.R and used by app.R
app.R is expected to provide the result on the screen and a downloadable report. I do not get the latter and I have been strugling the last two days with this.
Thank you very much!
app.R:
ui <- fluidPage(
titlePanel("Calculations"),
sidebarLayout(
sidebarPanel(
fileInput("file1","Select excel file with data", accept=c("excel",".xlsx",".xls")),
"When are available on the screen, you can download the report",
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
tableOutput(outputId = "tabla")
)
))
server <- function(input, output) {
source("./calculations.R")
output$tabla<-renderTable({
infile<-input$file1
if(is.null(infile))return(NULL)
calculo(infile$datapath)})
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')
# 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', overwrite = TRUE)
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
report.Rmd:
title: "Dynamic report"
output: word_document
knitr::opts_chunk$set(echo = FALSE,warning=FALSE,message = FALSE)
Results
print(output$tabla)
calculations.R
library(xlsx)
calculo<-function(archivo){
incrementos_descuentos<-read.xlsx(archivo,sheetName="incrementos - descuentos", check.names = FALSE)
incrementos_descuentos$`Desde / mm`<-as.numeric(as.character(incrementos_descuentos$`Desde / mm`))
incrementos_descuentos$`A / mm`<-as.numeric(as.character(incrementos_descuentos$`A / mm`))
incrementos_descuentos$`Volumen / L`<-as.numeric(as.character(incrementos_descuentos$`Volumen / L`))
incrementos_descuentos$`Resultado L/m`<-as.numeric(as.character(incrementos_descuentos$`Resultado L/m`))
incrementos_descuentos$`Resultado L/m`<-incrementos_descuentos$`Volumen / L`/(incrementos_descuentos$`A / mm`-incrementos_descuentos$`Desde / mm`)
Resutado<-incrementos_descuentos
Resutado
}
It seems that I found the solution, after many days.
I added in app.R a reactive object:
informe <- reactive({
infile<-input$file1
if(is.null(infile))return(NULL)
calculo(infile$datapath)
})
and the I called it from report.Rmd as informe()
I am trying to create a shiny application that allows users to enter text and upload an image. I would then like the text inputted by the user and image uploaded by the user to be downloaded as an html report in a similar format only with the headings, text, and image. My aim is to have multiple text boxes and associated images in a report that is downloaded.
I have the following code:
library(shiny)
library(rmarkdown)
ui <-
fluidPage(
titlePanel("QA Template"),
sidebarLayout(
sidebarPanel(
radioButtons('format', 'Document format', c('HTML'),
inline = TRUE),
downloadButton('downloadReport')
)),
mainPanel(
fluidRow(
h2("Presentation"),
column(5,h4("Titles"),
textAreaInput("inText", "Do titles properly convey
content?",height='100px',width='400px')),
column(1,h4("Upload Image"),
fileInput("file1",label="",
accept = c('image/png', 'image/jpeg','image/jpg')
)),
column(4,offset = 1,imageOutput('p1')))))
server <- function(input, output, session) {
inText<-reactive({textAreaInput()})
output$inText<-renderText({textAreaInput()})
file1 <- reactive({gsub("\\\\", "/", input$file1$datapath)})
output$p1<-renderImage({list(src = file1())})
downloadHandler(
filename =
paste("QA_report","file",".html",sep=""),
content = function(file) {
tempReport<-file.path(tempdir(),"QA_report.Rmd")
file.copy('QA_report.Rmd', tempReport,overwrite = TRUE)
##Parameters to pass
params <- list(text1=inText,pic1=file1)
rmarkdown::render(tempReport,output_file=file, params=params,
envir = new.env(parent = globalenv()))
}
)
}
shinyApp(ui = ui, server = server)
I also have this in the .Rmd:
---
title: "QA Template"
output: html_document
params:
text1: NA
pic1: NA
---
```{r include=FALSE}
library(knitr)
```
### Presentation
## Titles
# Do titles properly convey content?
```{r, results='asis',echo=FALSE,warning=FALSE}
print(params[["text1"]])
```
```{r, results='asis',echo=FALSE,warning=FALSE}
knitr::include_graphics(params[["pic1"]])
```
There is a small quirk with using renderImage() we need to set the deleteFile flag to FALSE. Otherwise, the file is read into the temp directory, displayed for the user and then deleted.
Not sure what you were trying to do here but it looks wrong textAreaInput is a UI function. You need to refer to the text flowing into the server with input$inText not output$inText or textAreaInput()
inText<-reactive({textAreaInput()})
output$inText<-renderText({textAreaInput()})
Here is the working code,
library(shiny)
library(rmarkdown)
ui <-fluidPage(
titlePanel("QA Template"),
sidebarLayout(
sidebarPanel(
radioButtons('format', 'Document format', c('HTML'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
fluidRow(
h2("Presentation"),
column(5,h4("Titles"),
textAreaInput("inText", "Do titles properly convey
content?",height='100px',width='400px')),
column(1,h4("Upload Image"),
fileInput("file1",label="",
accept = c('image/png', 'image/jpeg','image/jpg')
)),
column(4,offset = 1,imageOutput('p1'))
)
)
)
)
server <- function(input, output, session) {
file1 <- reactive({gsub("\\\\", "/", input$file1$datapath)})
output$p1<-renderImage({
req(file1())
browser()
list(src = file1())
},deleteFile = FALSE)
output$downloadReport <- downloadHandler(
filename =
paste("QA_report","file",".html",sep=""),
content = function(file) {
tempReport<-file.path(tempdir(),"QA_report.Rmd")
file.copy('QA_report.Rmd', tempReport,overwrite = TRUE)
##Parameters to pass
params <- list(text1=input$inText,pic1=file1())
rmarkdown::render(tempReport,output_file=file, params=params,
envir = new.env(parent = globalenv()))
}
)
}
shinyApp(ui = ui, server = server)
I would like to download Report within Shiny App, which includes Plotly graph.
So far i have not found any answer on stackoverflow.
Till this moment im able to download the screenshot of Plotly but it appears only in my working directory and it is not sent to Rmarkdown.
Example code:
library(shiny)
library(plotly)
library(rsvg)
library(ggplot2)
d <- data.frame(X1=rnorm(50,mean=50,sd=10),X2=rnorm(50,mean=5,sd=1.5),Y=rnorm(50,mean=200,sd=25))
ui <-fluidPage(
title = 'Download report',
sidebarLayout(
sidebarPanel(
helpText(),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'),
tags$script('
document.getElementById("downloadReport").onclick = function() {
var plotly_svg = Plotly.Snapshot.toSVG(
document.querySelectorAll(".plotly")[0]
);
Shiny.onInputChange("plotly_svg", plotly_svg);
};
')
),
mainPanel(
plotlyOutput('regPlot')
)
)
)
server <- function(input, output, session) {
output$regPlot <- renderPlotly({
p <- plot_ly(d, x = d$X1, y = d$X2,mode = "markers")
p
})
observeEvent(input$plotly_svg, priority = 10, {
png_gadget <- tempfile(fileext = ".png")
png_gadget <- "out.png"
print(png_gadget)
rsvg_png(charToRaw(input$plotly_svg), png_gadget)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('testreport.Rmd')
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'testreport.Rmd')
library(rmarkdown)
out <- render('testreport.Rmd', params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui = ui, server = server)
and testreport.Rmd file:
---
title: "test"
output: pdf_document
params:
name: "Test"
region: 'NULL'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Any help would be appreciated, because there is not many sources and documentations about R Plotly.
Cheers
If out.png is downloaded to your working directory, you can modify the content function of your downloadHandler to move it to the temporary directory and add it to the report:
content = function(file) {
temp_dir <- tempdir()
tempReport <- file.path(temp_dir, 'testreport.Rmd')
tempImage <- file.path(temp_dir, 'out.png')
file.copy('testreport.Rmd', tempReport, overwrite = TRUE)
file.copy('out.png', tempImage, overwrite = TRUE)
library(rmarkdown)
out <- render(tempReport, params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
Your testreport.Rmd could look like (more info here):
---
title: "test"
---
Here's the plot image.
![Plot image](out.png)
You could also pass the arguments of your plotly function in the render of your content function as explained here and use a parametrized Rmarkdown file but this only works for Html reports.
Depending on how deep you want to dive into this, I would suggest creating a .brew file with your shiny code and than you can have your user send the information to the brew file and create the plot. This would give you a static code file which is updated dynamically with new data, each time. The only draw back is that when you make changes to shiny you have to make the same changes to your brew file. The other option is to create a flex dashboard with rmarkdown using the new RStudio 1.0 which becomes a html file.
See (Create parametric R markdown documentation?) for brew example.
I am really struggling to get this one down. I have searched here and all over but I am not sure what I am doing wrong. I apologize as this maybe a really silly question.But I am a novice.
I have put in place a shiny application, where it renders an existing R markdown file which is compiled based on the Shiny inputs. In the end I get what is like a PDF file. Everything works fine except for the option to download. When I push the download, it just opens another webpage session from the beginning.
How can get the final document displayed as an PDF file downloaded. Really appreciate any help.
I edited this code based on a shiny example, but still cannot get to the bottom of this. When I click on the download button it opens another session.
Edited code
library(shiny)
library(knitr)
shinyServer(function(input, output,session) {
library(knitr)
output$markdown <- renderUI({
HTML(markdown::markdownToHTML(knit('RMarkdown_pdf1.Rmd', quiet = TRUE)))
})
output$downloadData <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
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', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
})
library(shiny)
library(knitr)
shinyUI(
fluidPage(
titlePanel("Drift Report - Beta Version 1.0"),
selectInput("n",
"Number of files:",
choices = c(1,2,3,4)),
checkboxInput("d", label = "Data Summary", value = FALSE),
checkboxInput("k", label = "Drift Plots", value = FALSE),
radioButtons("p", label = "Plot Type",
choices = list("Point Plot" = 1, "Cumm Plot"=2, "Both - Side by Side"=3, "Both - One underneath the Other"=4),selected = NULL,inline=TRUE),
sliderInput("s","No of Plots", min = 1, max = 50, value = 10, width = "40%"),
submitButton("Apply Changes"),
conditionalPanel(
condition = "input.n == 1",
fileInput("dat","File Upload for Analysis", accept = ".eff")
),
radioButtons('format', 'Document format for Download', c('PDF', 'HTML', 'Word'),
inline = TRUE),
conditionalPanel(
condition = "input.n == 2",
fileInput("dat","1st File Upload for Analysis"),
fileInput("dat3","2nd File Upload for Analysis")
),
downloadButton('downloadData', 'Download'),
uiOutput('markdown')
)
)
log
2016-04-26T18:50:56.177858+00:00 shinyapps[98254]: Warning in file(filename, "r", encoding = encoding) :
2016-04-26T18:50:56.177862+00:00 shinyapps[98254]: cannot open file 'datEff.R': No such file or directory
2016-04-26T18:50:56.178919+00:00 shinyapps[98254]: Quitting from lines 10-45 (RMarkdown_pdf1.Rmd)
2016-04-26T18:50:56.180088+00:00 shinyapps[98254]:
2016-04-26T18:50:56.182026+00:00 shinyapps[98254]: cannot open the connection
2016-04-26T18:50:56.182763+00:00 shinyapps[98254]: Warning: Error in file: cannot open the connection
2
The id of your download button is downloadData but in server code you used downloadReport. They don't match.