How to pass "reactive" data into R Markdown as a parameter? - r

I want to be able to pass a reactive data.table to my Rmarkdown document that will sort the table and print the top, say 5, sorted entries.
I keep running into "Error : x must be a data.frame or data.table" at setorderv. I suspect the reactive is upsetting the is.data.table checks.
How do I simply pass a copy of the data to the Rmd document? And remove the reactivity wrapper?
Here is a simplified example cobbled from reactivity and downloadHandler stock examples. I took at look at this on SO which suggested using observe but I am not sure how to implement this. Thanks I appreciate some help on this.
RMARKDOWN - SOtestreport.Rmd
---
title: "Top in Segment Report"
output: html_document
params:
n: 5
dt: NA
top.field: NA
---
```{r setup, echo = FALSE}
library(data.table)
library(knitr) # for kable
```
Data report as at: `r format(Sys.time(), "%a %b %d %Y %X")`
```{r, echo = FALSE}
table.str <- paste0("Showing Top ", params$n ," tables for these fields: ",
params$top.field)
# is this the best way of having dynamic labels?
```
`r table.str`
```{r, echo = FALSE}
# tried this
# test.dt <- copy(dt)
# normally a function GenerateTopTable with limit sort field etc.
setorderv(dt, params$top.field, -1) # -1 is descending. THIS IS WHERE IT CRASHES
out <- dt[1:params$n,]
```
```{r toptable, echo = FALSE}
kable(out, digits = 3)
```
app.R
# SO test report
# mini example based on https://shiny.rstudio.com/gallery/reactivity.html
library(shiny)
library(datasets)
server <- function(input, output) {
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars)
})
output$caption <- renderText({
input$caption
})
output$summary <- renderPrint({
dataset <- datasetInput()
summary(dataset)
})
output$view <- renderTable({
head(datasetInput(), n = input$obs)
})
# PROBLEM BIT WHERE I AM ADDING ON GALLERY EXAMPLE
# handler from https://stackoverflow.com/questions/37347463/generate-report-with-shiny-app-and
output$topreport <- downloadHandler(
filename = "topreport.html",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "SOtestreport.Rmd")
file.copy("SOtestreport.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
# TRIED THIS TOO
# my.dt <- as.data.table(datasetInput())
my.dt <- datasetInput()
my.params <- list(n = input$obs,
dt = my.dt,
top.field = names(my.dt)[1])
rmarkdown::render(tempReport, output_file = file,
params = my.params,
envir = new.env(parent = globalenv())
)
}
)

I fixed this example - dt in Rmd was not prefaced with params$!
setorderv(params$dt, params$top.field, -1) # -1 is descending
out <- params$dt[1:params$n,]
I still looking for answers on whether this is the right approach above (in passing parameters in Shiny to RMarkdown apps).
I also want to point out to others that these answers were also useful:
use of ReactiveValues by #NicE https://stackoverflow.com/a/32295811/4606130
What's the difference between Reactive Value and Reactive Expression?
I also made use of copying the dataset to break the reactivity, i.e.
my.dt <- copy(params$dt)
#do this before passing into render params list
Another tip in RStudio is not to use the internal Viewer Pane but to run externally in the browser. This fixed where the temporary file was saved issues. You can choose to always Run Externally under Run App in image below:

Related

Inline code not executed in a shiny app with Rmarkdown report

Dear all shiny developers!
I have a question about a shiny app with a Rmarkdown report downloadable.
The app is based on this https://shiny.rstudio.com/articles/generating-reports.html, taken here as an exemple.
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 100, 50),
downloadButton("report", "Generate report")
),
server = function(input, output) {
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.pdf",
content = function(filename) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "Template.Rmd")
print(tempReport)
file.copy("Template.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(n = input$slider)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = filename,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
with my .Rmd document
---
title: ''
output: pdf_document
geometry: "left=2cm,right=2cm,top=1cm,bottom=2cm"
params:
n: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `r params$n` random points.
The code is running ok, the document is created but when I open it, I can see that the code within the chunk is ok but not in the inline code, see below:
However, in this exemple https://shiny.rstudio.com/gallery/download-knitr-reports.html we see that the inline code is good (I don't have the code of the Rmarkdown unfortunatelly).
I saw this subject (https://community.rstudio.com/t/embedding-shiny-with-inline-not-rendering-with-html-output/41175) that could be similar but it is html and the answer does not seem to fit.
Do you have an idea why it does not function ? Or any track to explore ?
Many thanks !!
Be careful to the file.copy function !
Thanks to the remark of Limey, I notice that the Rmarkdown that had a typo few moments ago was not updated! Careful that the file.copy is correct!
Here is the script working:
shinyApp(
ui = fluidPage(
sliderInput("slider", "Slider", 1, 100, 50),
downloadButton("report", "Generate report")
),
server = function(input, output) {
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.pdf",
content = function(filename) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "rules.Rmd")
print(tempReport)
file.copy("Data/rules.Rmd", tempReport, overwrite = TRUE)
# Set up parameters to pass to Rmd document
params <- list(n = input$slider)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = filename,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
)
and the Rmarkown
---
title: ''
output: pdf_document
geometry: "left=2cm,right=2cm,top=1cm,bottom=2cm"
params:
n: NA
---
```{r}
# The `params` object is available in the document.
params$n
```
A plot of `r params$n` random points.
Thanks to all of you that gave time to this subject!

Is there a way to have the output of a function in R be an R markdown chunk?

I'm working on a project to make it easier to create flex/shiny dashboards from qualtrics surveys. I'd really like to be able to write a couple functions that would let co-workers who have less experience with R be able to make similar documents without having to know Rmarkdown syntax.
For example, if someone wanted to make a one page dashboard with a scatterplot, I'd like to be able to have them use a couple functions like (make_dashboard, make_page) etc:
make_dashboard(
title = "Qualtrics Report Dashboard",
page 1 = make_page(header = "Page 1", format = "column", render = "plot",
data = survey_data, variables = c("var1", "var2"))
)
which would then create a rmd file with this:
---
title: "Qualtrics Report Dashboard"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: scroll
runtime: shiny
---
Page 1
=====================================
renderPlot( {
ggplot(data = survey_data, mapping = aes_string(x = var1,
y = var2)) +
geom_point() +
labs(x = get_label(get(var1, survey_data)),
y = get_label(get(var2, survey_data)))
}
)
I haven't gotten very far with trying to write these functions / implement this logic, because I'm not even sure if I'm thinking about it in the right way - is it possible to create rmarkdown chunks with functions like this?
I've looked at other posts 1 and 2 about child documents in knitr, but I don't really want every chunk to be the same, rather have the person be able to change certain aspects (e.g. type of plot, data, etc.).
Not sure if this will be useful to anyone else, but I ended up using whisker (https://github.com/edwindj/whisker), which can render strings into documents to construct an Rmd in the style of flexdashboard.
TLDR: Essentially I made functions that create strings of text matching the building blocks of flexdashboard. With whisker, you can pass in variables by encasing words in the string with two bracket parentheses and then assigning their values with a list of var_name = value for each variable in the string, e.g.
template <- "My name is {{name}}."
d <- list(name = "Emily")
cat(whisker.render(template, data = d))
print(d)
My name is Emily
I used a combination of this and the str_c from stringr to construct strings for different elements of the flexdashboard, allowing the user to input variables like title, variable for plots, etc. that then could be rendered into the string using whisker. Then, I joined all of those strings together and render it into an Rmd file. Honestly, I am not sure this is actually easier for people who don't know R to use, and I'll probably end up doing something different, but I wanted to share in case anyone is thinking about this.
Example: running the chunk below creates a file called "test_dashboard.Rmd" with the text format for a flexdashboard with a 1 input sidebar and a single page with one plot.
```
make_dashboard(title = "Test Dashboard",
sidebar = make_sidebar(sidebar_title = "here is the input",
input_type = "multi-select",
input_name = "Interesting Var #1"),
page1 = make_page(page_title = "Cool Plots!",
element_one = make_plot(plot_title = "this is my plot",
type = "bivariate",
vars = c("cool_var1",
"cool_var2"))),
fn = "test_dashboard")
```
OUTPUT:
```
---
title: Test Dashboard
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: scroll
runtime: shiny
---
\```{r setup, include=FALSE}
library(flexdashboard)
library(tidytext)
library(tidyverse)
library(janitor)
library(DT)
library(gghighlight)
library(knitr)
library(shiny)
library(qualtRics)
library(curl)
library(sjlabelled)
library(naniar)
library(scales)
library(lme4)
library(MASS)
library(snakecase)
\```
\```{r global, include=FALSE}
#setting global options for table scrolling and plot theme
options(DT.options = list(scrollY="100vh"))
theme_set(theme_minimal())
#this fetches all of your survey info
surveys <- all_surveys()
#this saves the survey responses into
docusign_survey <- fetch_survey(surveyID = surveys$id[1],
verbose = TRUE,
label = TRUE,
breakout_sets = TRUE,
force_request = TRUE)
#this saves the question text into a dataframe
questions <- survey_questions(surveyID = surveys$id[1])
rename_df <- rename_variables(docusign_survey)
#this renames all of the variables
docusign_survey <- docusign_survey %>%
rename_at(as.vector(rename_df$old_name), ~ as.vector(rename_df$new_labels))
#new variables
new_var <- rename_df$new_labels
#which are multi_select?
multi_select <- rename_df %>%
filter(ms == 1) %>%
dplyr::select(new_labels)
#relabel those NAs as No
docusign_survey <- docusign_survey %>%
purrr::modify_at(multi_select$new_labels, na_to_y)
\```
Sidebar {.sidebar}
=====================================
here is the input
\```{r}
selectInput("p_var_1", label = "Interesting Var #1",
choices = new_var,
multiple = TRUE)
\```
Cool Plots!
=====================================
Column {.tabset}
-------------------------------------
### this is my plot
\```{r}
renderPlot( {
make_bivariate_plot(docusign_survey, input$cool_var1, input$cool_var2)
})
\```
```
Functions
make_dashboard()
I saved the parts that will repeat every time, probably will want to make them editable for changes in scrolling, etc. but just trying to make proof of concept at the moment.
```
make_dashboard <- function(title, sidebar, page1, fn){
load("data/top_matter.rda")
load("data/libraries.rda")
load("data/main_chunk.rda")
initial_bit <- stringr::str_c(top_matter, libraries, main_chunk, sep = "\n\n")
intermediate <- stringr::str_c(initial_bit, sidebar, sep = "\n\n")
total <- stringr::str_c(intermediate, page1, sep = "\n\n")
data <- list(title = title)
out_fn <- paste0("./", fn, ".Rmd")
writeLines(whisker.render(total, data), con = out_fn)
}
```
make_sidebar()
```
make_sidebar <- function(sidebar_title, input_type, input_name){
top_sidebar <-
'Sidebar {.sidebar}
=====================================
'
sidebar_text <- str_c(top_sidebar, sidebar_title, sep = "\n\n")
if(input_type == "multi-select"){
ms <- "TRUE"
} else {
ms <- "FALSE"
}
input_one <- make_select_input(input_name, ms)
sidebar_total <- str_c(sidebar_text, "```{r}", input_one, "```", sep = "\n\n")
return(sidebar_total)
}
```
make_page()
```
make_page <- function(page_title, element_one){
top_page <-
'{{page_title}}
=====================================
Column {.tabset}
-------------------------------------'
add_element <- stringr::str_c(top_page, element_one, sep = "\n\n")
data <- list(page_title = page_title)
page <- whisker.render(add_element, data = data)
return(page)
}
```
make_plot()
```
make_plot <- function(plot_title, type = c("univariate", "bivariate"), vars){
top_plot_piece <-' {{plot_title}}
\```{r}
renderPlot( {
'
if(type == "univariate"){
plot_piece <-
'make_univariate_plot(docusign_survey, input${{vars}})
})
\```'
total_plot <- stringr::str_c(top_plot_piece, plot_piece, sep = "\n\n")
data <- list(plot_title = plot_title,
vars = vars)
plot_chunk <- whisker.render(total_plot, data = data)
} else{
plot_piece <-
'make_bivariate_plot(docusign_survey, input${{var_1}}, input${{var_2}})
})
\```'
total_plot <- stringr::str_c(top_plot_piece, plot_piece, sep = "\n\n")
data <- list(plot_title = plot_title,
var_1 = vars[1],
var_2 = vars[2])
plot_chunk <- whisker.render(total_plot, data = data)
}
return(plot_chunk)
}
```

How to display R Shiny output in R Markdown?

I'm new to R markdown here and I am trying to create an R Shiny app which I can enter a list of names, and then download the output (like a name list) as HTML file. I am using R markdown to create the HTML file. Here are my sample codes:
R Shiny:
library(shiny)
ui <- list(
textInput("name", "Type new text input name", value = ""),
actionButton("btn", "click me to create text input"),
uiOutput("newInputs"),
downloadButton("download_report", "Download")
)
server <- function(input, output)
{
family_member <- reactiveValues(
add_family_info = list()
)
observeEvent(input$btn, {
newid <- paste(length(family_member$add_family_info))
family_member$add_family_info <- c(family_member$add_family_info, list(c(newid, input$name)))
family_member
})
output$newInputs <- renderUI({
lapply(family_member$add_family_info, function(a)
c(paste(a[2])))
})
output$download_report <- downloadHandler(
filename = "name.html",
content = function(file) {
tempReport <- file.path(tempdir(), "name.Rmd")
file.copy("name.Rmd", tempReport, overwrite = TRUE)
params <- list(report = uiOutput("newInputs"))
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv()))
}
)
}
runApp(list(ui = ui, server = server))
R Markdown:
---
runtime: shiny
output: html_document
params:
report: NA
---
\
\
# Member names
`r params$report`
Appreciate any help! Thanks in advance!!!!
If you are just using a Shiny to render an Rmarkdown document, you don't need the runtime of the document to be Shiny. This is only needed if the document itself will ultimately be a shiny app.
Looking at the download handler
params <- list(report = uiOutput("newInputs"))
The uiOutput function generates the html for the element. It doesn't retrieve the values (you can see this if you run execute it in the console by itself). Additionally newInputs just refers to the container for the text (it's not actually inputs). Instead, you would want to use the reactive value storing the list
params <- list(report = family_member$add_family_info)
However, since this will be printed it can't be an arbitrary R object. It has to be something that cat can handle. In this case family_member$add_family_info is a list of list. Try flattening it with something like
params <- list(report = unlist(family_member$add_family_info))

organize reactivity with pre-loaded data

I have couple of tables stored each in a separate txt file, and also combined in a single Rdat file, something like this:
# generate tables
df.A <- data.frame(colA1=letters[1:20],colA2=LETTERS[1:20], stringsAsFactors = F)
df.B <- data.frame(colB1=rnorm(20),colB2=rnorm(20), stringsAsFactors = F)
# save tables as separate files
write.csv(df.A, 'tableA.txt')
write.csv(df.B, 'tableB.txt')
# I may have more tables
# save all tables in a single Rdat file
save(df.A,df.B, file = 'alldata.RDat')
Now in my shiny markdown document, I want to pre-load those tables from the RDat file, but also give user a possibility to re-load them a) separately from individual files, or b) altogether from the RDat file. Here is the first version I came to:
---
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
load('alldata.RDat')
```
Tables below:
```{r}
inputPanel(
actionButton('load.A','Reload Table A'),
actionButton('load.B','Reload Table B'),
actionButton('load.Rdat','Load all from Rdat file')
)
tabsetPanel(type = "tabs",
tabPanel("table A", dataTableOutput("toA")),
tabPanel("table B", dataTableOutput("toB"))
)
# next 2 lines render pre-loaded tables before any buttons are pressed:
output$toA <- renderDataTable(df.A, options=list(pageLength=5))
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
observeEvent(input$load.A, {
df.A <- read.csv('tableA.txt');
output$toA <- renderDataTable(df.A, options=list(pageLength=5))
})
observeEvent(input$load.B, {
df.B <- read.csv('tableB.txt');
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
})
observeEvent(input$load.Rdat, {
load('alldata.RDat', verbose = T);
output$toA <- renderDataTable(df.A, options=list(pageLength=5));
output$toB <- renderDataTable(df.B, options=list(pageLength=5))
})
```
It works fine, but I have a feeling it is not the proper way to use reactivity. For example, every time after updating my table object (df.A or dfB), I have to call render explicitly output$toA <- renderDataTable(...) (3 times for each table!).
One solution I had in mind was to put my tables into reactiveValues(), which gave the following:
---
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
load('alldata.RDat')
```
Tables below:
```{r}
inputPanel(
actionButton('load.A','Reload Table A'),
actionButton('load.B','Reload Table B'),
actionButton('load.Rdat','Load all from Rdat file')
)
tabsetPanel(type = "tabs",
tabPanel("table A", dataTableOutput("toA")),
tabPanel("table B", dataTableOutput("toB"))
)
rv <- reactiveValues(df.A = df.A, df.B = df.B)
output$toA <- renderDataTable(rv$df.A, options=list(pageLength=5))
output$toB <- renderDataTable(rv$df.B, options=list(pageLength=5))
observeEvent(input$load.A, {
rv$df.A <- read.csv('tableA.txt');
})
observeEvent(input$load.B, {
rv$df.B <- read.csv('tableB.txt');
})
observeEvent(input$load.Rdat, {
load('alldata.RDat', verbose = T);
rv$df.A <- df.A;
rv$df.B <- df.B;
})
```
This looks better because I have only one call of each renderDataTable() in my code. But now each of my tables are stored in memory twice - one in df.A (as loaded from 'alldata.RDat') and another one in rv$df.A... Does it make sense at all, or there's a more kosher way to solve these kinds of things?
You would like to load the data for df.A and df.B from either a csv or Rdat file. This almost certainly requires an intermediate variable, rv as you have correctly created.
The second example you have created is much better than the first, we must avoid multiple render calls to the same output, especially render calls inside an observer.
The code below executes load('alldata.RDat', verbose = T) from within the observer and the initial values of rv are set from within the observer instead of using the global load('alldata.RDat', verbose = T). This prevents the data from being loaded twice.
---
runtime: shiny
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
#load('alldata.RDat')
```
Tables below:
```{r}
inputPanel(
actionButton('load.A','Reload Table A'),
actionButton('load.B','Reload Table B'),
actionButton('load.Rdat','Load all from Rdat file')
)
tabsetPanel(type = "tabs",
tabPanel("table A", dataTableOutput("toA")),
tabPanel("table B", dataTableOutput("toB"))
)
rv <- reactiveValues(df.A = NULL, df.B = NULL)
output$toA <- renderDataTable({
req(rv$df.A)
rv$df.A
}, options=list(pageLength=5))
output$toB <- renderDataTable({
req(rv$df.B)
rv$df.B
}, options=list(pageLength=5))
observeEvent(input$load.A, {
rv$df.A <- read.csv('tableA.txt');
})
observeEvent(input$load.B, {
rv$df.B <- read.csv('tableB.txt');
})
observeEvent(c(input$load.Rdat), {
load('alldata.RDat', verbose = T);
rv$df.A <- df.A;
rv$df.B <- df.B;
})
```

Rmarkdown : exporting table1 descriptive statistics through shiny app

I am working on a shiny app which takes user datas in input and complete first classical descriptive statistics and then a full statistical analysis. Indeed, the descriptive statistic part is done with table1 package table1 documentation used. At the end of the app I want to allow the user to download a full report containing all the plot and tables (especially descriptive statistic tables).
I am able to write some Rmarkdown scripts to include ggplots and DT datatables in the report. The problem is about the table1 object.
I render them using renderUI in the server part and uiOutput in the ui part.
Here is the code used :
Shiny script
library(shiny)
library(sas7bdat)
library(dplyr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(factoextra)
library(FactoMineR)
library(corrplot)
library(cluster)
library(NbClust)
library(clValid)
library(dendextend)
library(summarytools)
library(RColorBrewer)
library(table1)
options(shiny.maxRequestSize=30*1024^2)
ui <-fluidPage(
navlistPanel(
#Welcome Page with logo and explanations
tabPanel("Welcome",textOutput("welcome_message"),textOutput("welcome_message_2"),img(src="logo_danone.jpg", height = 350, width = 350)),
#Selector for file upload
tabPanel("Input Datas",fileInput('datafile_LB', 'Choose LB Database file',
accept=c('text/csv', 'text/comma-separated-values,text/plain')),
fileInput('datafile_DS', 'Choose DS Database file',accept=c('text/csv', 'text/comma-separated-values,text/plain')),
fileInput('datafile_VS', 'Choose VS Database file',accept=c('text/csv', 'text/comma-separated-values,text/plain')),
fileInput('datafile_SV', 'Choose SV Database file',accept=c('text/csv', 'text/comma-separated-values,text/plain')),
fileInput('datafile_DM', 'Choose DM Database file',accept=c('text/csv', 'text/comma-separated-values,text/plain'))),
# Display of the input data without any modification
tabPanel("Raw Datas",
DT::dataTableOutput("filetable_LB"), radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE), downloadButton('downloadReport')
),
tabPanel("test plot", plotOutput("graph")),
tabPanel("Disposition of subjects", uiOutput("disposition"))
))
##### Server part #####
server <- function(input, output, session ) {
# Seting directory and import dependent functions
##### Input Loading #####
filedata_LB <- reactive({
infile <- input$datafile_LB
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
read.sas7bdat(infile$datapath)
})
filedata_DS <- reactive({
infile <- input$datafile_DS
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
read.sas7bdat(infile$datapath)
})
tableau <- reactive({table1(~ DSDECOD, data= filedata_DS(), topclass="Rtable1-zebra")})
#######################################################################################################################
################################# #################################
################################# Primary Endpoint Output #################################
################################# #################################
#######################################################################################################################
#This previews the CSV data file
output$filetable_LB <- DT::renderDataTable({DT::datatable(filedata_LB())})
output$graph <- renderPlot({ggplot(data = filedata_LB(), aes(y = LBSTRESN)) + geom_boxplot()})
output$disposition <- renderUI(print(table1(~ DSDECOD, data= filedata_DS(), topclass="Rtable1-zebra")))
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- "C:/Users/graditse/Desktop/test_markdown/report_file.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)
}
)
}
shinyApp(ui, server)
Rmd script
---
title: "test"
author: "seb"
date: "26 juin 2019"
output: html_document
always_allow_html: yes
---
```{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}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
```{r, fig.align='center', fig.pos='htb!', echo=FALSE, cache=FALSE, warning = FALSE, message = FALSE, tidy=TRUE}
library(DT)
library(webshot)
datatable(filedata_LB(),rownames=FALSE, options = list(dom='t',ordering=F))
```
```{r, echo=FALSE}
# library(ggplot2)
# p <- ggplot(data = filedata_LB(), aes(y = LBSTRESN)) + geom_boxplot()
# p
output$graph
```
```{r, echo=False}
library(webshot)
library(table1)
library(shiny)
reactive(table1(~ DSDECOD, data= filedata_DS(), topclass="Rtable1-zebra", output = "markdown"))
```
When I try to download the report, this can't be done I got :
Warning: Error in $.shinyoutput: Reading objects from shinyoutput object not allowed.
[No stack trace available]
I don't really know how to handle this problem. This is strange because the DT table is also reactive and can be displayed into the report.
Is there a solution to display readable descriptive statistic tables into the Shiny app and in the report ?
I used the table1 package beacause it offers th possibility to process continuous and discrete variables, on different groups.
Thanks in advance !

Resources