Why I do not get my data under the Load Data Panel? - shiny

I am having two tabs in the navigation bar (I am trying to keep it simple, I have more, but won't matter). Now, I get my info tab the way I want it. But when I upload the module for load data, I cannot get it under 'Load Data' tab but rather under the first tab - Info .
Here is a snipped of the code (although I can give access to the repo upon request - https://github.com/gabrielburcea/grwtgolem), it is golem shiny framework and would like to keep it this way.
First, I define app_ui :
app_ui <- function(request) {
tagList(# Leave this function for adding external resources
golem_add_external_resources(),
shinyjs::useShinyjs(),
# Your application UI logic
shinyUI(
shiny::navbarPage(title = div(tags$a(img(src = "www/AZ_SYMBOL_RGB.png", height = "50px"), "Growth Rate Explorer"),
id = "navBar",
theme = "www/style.css",
# collapsible = TRUE,
# inverse = TRUE,
style = "position: relative; top: -30px; margin-left: 10px; margin-top: 5px;"),
header = tags$head(includeCSS("www/style.css")),# sourcing css style sheet
# make navigation bar collapse on smaller screens
windowTitle = "Growth Rate Explorer",
collapsible = TRUE,
shiny::tabPanel("Info", icon = icon("fa-light fa-info"), mod_info_app_ui("info_app_1")),
shiny::tabPanel("Load Data", icon = icon("fa-light fa-database"), mod_load_app_ui("load_app_1"))
)
)
)
}
And then, I define the server_app as:
#' app_server
#'
#' #param input,output,session Internal parameters for {shiny}.
#' DO NOT REMOVE.
#' #import shiny
#' #noRd
app_server <- function(input, output, session){
mod_info_app_server("info_app_1")
mod_load_app_server("load_app_1")
}
To reiterate, I get my load app under the info tab. Why is this happening?
I have tried for the last two days different configuration but nothing helped.
I tried to re-define the app_server with the shiny::callModule(mod_load_server, mod_load_ui_1) and it did not work whatsoever.
For your info: mod_info_app and mod_load_app:
First is mod_info_app that contains html scripts (which I won't provide, these are way too big) but this module defines the ui and server for info tab, just as golem requires:
#'mod_info_app_ui UI Function
#'
#' #description A shiny Module.
#'
#' #param id,input,output,session Internal parameters for {shiny}.
#'
#' #noRd
#'
#' #importFrom shiny NS tagList
mod_info_app_ui <- function(id){
ns <- NS(id)
tagList(
tagList(shiny::tabPanel(title = "Info",
tags$div(
class = "main",
shiny::fluidPage(
htmltools::htmlTemplate("www/welcome_to_growth_rate_explorer.html"),
htmltools::htmlTemplate("www/info_tabs_list.html")
)
)))
)
}
#' mod_info_app_server Server Functions
#'
#' #noRd
mod_info_app_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
# Color coding
colorCoding <- reactive({
tagList(
tags$b("Legend"),
tags$p(drawBullet(color = paste(myColors[1], "; border: 1px solid black")), "Adjusted p Value > 0.05"),
tags$p(drawBullet(color = myColors[2]), "0.01 < Adjusted p Value", HTML("≤"), "0.05"),
tags$p(drawBullet(color = myColors[3]), "0.001 < Adjusted p Value", HTML("≤"), "0.01"),
tags$p(drawBullet(color = myColors[4]), "0.0001 < Adjusted p Value", HTML("≤"), "0.001"),
tags$p(drawBullet(color = myColors[5]), "Adjusted p Value", HTML("≤"), "0.0001")
)
})
output$info_colorCoding <- renderUI(colorCoding())
etc, etc,
})
}
Then comes the mod_load_app, with ui and server defined, it is a bit long but just for yourself to make yourself:
#' mod_load_app_ui UI Function
#'
#' #description A shiny Module.
#'
#' #param id,input,output,session Internal parameters for {shiny}.
#'
#' #noRd
#'
#' #importFrom shiny NS tagList
mod_load_app_ui <- function(id) {
ns <- NS(id)
tagList(shiny::tabPanel(
title = "Load Data",
tags$br(),
shiny::sidebarLayout(
shiny::sidebarPanel(
hidden(
actionButton(
inputId = "load_loadNewButton",
icon = icon("arrow-alt-circle-up"),
label = "Upload new data"
)
),
# Load data
div(
id = "load_inputDataSpecifics",
fileInput(
inputId = "load_file",
label = "Data File(s)",
accept = c(".csv", ".xlsx"),
multiple = TRUE
),
uiOutput("load_selectColumnNamesUI"),
uiOutput("load_dayOffsetInput"),
uiOutput("load_loadDataButtonUI")
),
uiOutput("load_warnings"), etc, etc, etc, etc
)
)
)
)
))
}
#' mod_load_app_server Server Functions
#'
#' #noRd
mod_load_app_server <- function(id){
moduleServer( id, function(input, output, session){
ns <- session$ns
observe({
req(results$load_dataType())
if(length(input$load_loadDataButton) ==1){
toggleElement(id = "load_MBPlotFacet", condition = results$load_dataType() ==2)
}
toggleElement(id = "load_excludeIdSelect", condition = input$load_outlierType %in% c(1,3))
toggleElement(id = "load_excludeButton", condition = isTruthy(input$load_excludeReason))
toggleElement(id = "load_excludeDaySelect", condition = input$load_outlierType %in% c(2,3))
})
observe({
req(results$load_dataVolume())
updateSelectInput(session,
inputId= "load_excludeDaySelect",
choices = sort(unique(results$load_dataVolume()$day)))
sortedIds <- list()
for(treatment in levels(results$load_dataVolume()$treatment)){
ids <- unique(results$load_dataVolume()$animal_id[results$load_dataVolume()$treatment == treatment])
sortedIds[[treatment]] <- ids
}
updateSelectInput(session, inputId= "load_excludeIdSelect", choices = sortedIds)
})
output$load_selectColumnNamesUI <- renderUI({
req(results$load_dataInputFile0())
myColumns <- matchColumns(results$load_dataInputFile0())
names <- names(myColumns)
inputIds <- paste0("load_columnName_", names)
tagList(
textInput("load_dayOffset",
label = "Specify how day is defined",
value = "Post-implant"),
helpText("Please check whether the program has detected the right columns"),
lapply(1:length(myColumns), function(i)
selectizeInput(inputId = inputIds[i],
label = names[i],
choices = myColumns[[i]]$options,
selected = myColumns[[i]]$guess))
)
}) etc, etc, etc..
}
## To be copied in the UI
# mod_load_app_ui("load_app_1")
## To be copied in the server
# mod_load_app_server("load_app_1")
....... Adding more ----------
If you look, as you can see the body page appears under both tabs regardless of which I choose
Second pic
And the third pic with load data info mixed up with Info Tab:

Related

Usage of Modules and stratégie du petit r with navbarPage

I try to understand the usage of modules and stratégie du petit r.
I would like to receive feedback if I used the components correctly?
Also I'm interested: Does it make sense to structure an application in the way that each tabPanel is 1 Module? For Example File Upload, Overview, Clustering, and Reporting.
For this, I built a small application.
A navBarpage with 2 panels. For each tabPanel one module exists which creates the UI and contains the server logic for the panel.
tabPanel 1 / Module "something"
numeric Input -> user can choose between 1,2,3
action button. When pressed the panel View changes.
tabPanel 2 / Module "happend"
shows the chosen number
app_ui (UI-structure and calls module UI)
server_ui (calls Module Servers)
mod_something (Numberinput and actionButton to change panel)
mod_happend ( Displays number)
`
app_ui
app_ui <- function(request) {
tagList(
# Leave this function for adding external resources
golem_add_external_resources(),
# Your application UI logic
fluidPage(
navbarPage("navBarPage",
id = "navBarID",
tabPanel("title1",
mod_something_ui("something_1")),
tabPanel("title2",
mod_happend_ui("happend_1")),
)
)
)
}
app_server
app_server <- function(input, output, session) {
# Your application server logic
r <- reactiveValues()
#mod_Navigation_server("navigation1",r)
mod_something_server("something_1", r = r,parent = session)
mod_happend_server("happend_1",r)
#?moduleServer
}
mod_something
mod_something_ui <- function(id){
ns <- NS(id)
tagList(
selectInput(inputId = ns("numberInput"), label = "choose", choices = c(1,2,3)),
actionButton(inputId = ns("doSomething"),label = "Change Page!"),
)
}
mod_something_server <- function(id,r,parent){
moduleServer(id, function(input, output, session){
ns <- session$ns
observe({
r$numberInput <- input$numberInput
})
observeEvent(eventExpr = input$doSomething,
updateNavbarPage(session = parent, inputId = "navBarID", selected = "title2"))
})
}
mod_happend
mod_happend_ui <- function(id){
ns <- NS(id)
tagList(
p("the Number is"),
textOutput(ns("choosenNumber")),
)
}
#' happend Server Functions
#'
#' #noRd
mod_happend_server <- function(id,r){
moduleServer( id, function(input, output, session){
ns <- session$ns
number <- reactive(r$numberInput)
output$choosenNumber <- renderText(number())
})
}
`

R Shiny: use different .Rmd files to generate reports based on radio button selection

I am updating a Shiny app to add two selection radio buttons. I want to use different .Rmd files to create different reports. They will be using different R scripts with different calculations. The tool previously had no selection option and looked like this:
ui.R
ui <- navbarPage(
tags$head(HTML("<script type='text/javascript' src='www/custom_work.js'></script>")),
tabPanel("Main",
includeScript(path = 'www/custom_work.js'),
# https://rstudio.github.io/shinythemes/
sidebarLayout(
sidebarPanel(width=3,
# Input: Select a file ----
fileInput("file1", "Choose Excel file",
multiple = FALSE,
c("application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")),
conditionalPanel(
condition = "output.hot_assay_info",
downloadButton("downloadReport", "Download Report", class ='btn-success')
)
),
mainPanel(
radioButtons(inputId = "type", "Select Type:", choices = c("Up", "Down")),
radioButtons(inputId = "class", "Select Class:", choices = c("Left", "Right")),
tabsetPanel(
tabPanel("A", dataTableOutput("hot_A")),
tabPanel("B", rHandsontableOutput("hot_B", width = "100%", height = 700)),
tabPanel("C", rHandsontableOutput("hot_C", width = "100%", height = 700)),
)
)
)
)
)
server.R
server <- function(input, output, session) {
values <- reactiveValues()
observe({print(input$file1)})
# Observer A Info
observe({
req(input$file1$datapath)
DF <- read_excel(input$file1$datapath, sheet = "A")
values[['A']] <- DF
})
# Observer B Results
observe({
req(input$file1$datapath)
DF <- read_excel(input$file1$datapath, sheet = "B")
values[['B']] <- DF
})
# Observer C Controls
observe({
req(input$file1$datapath)
DF <- read_excel(input$file1$datapath, sheet = "C")
values[['C']] <- DF
})
output$hot_assay_info <- renderDataTable({
req(input$file1$datapath)
DF <- values[["A"]]
})
# Render Screening Table
output$hot_screening <- renderRHandsontable({
req(input$file1$datapath)
DF <- values[["B"]]
})
# Render Normalization Table
output$hot_normalization <- renderRHandsontable({
req(input$file1$datapath)
DF <- values[["C"]]
})
output$downloadReport <- downloadHandler(
filename = function(){
input$filename
},
content = function(filename) {
rmarkdown::render('test.Rmd',
output_file = filename,
params = list(df_values = values))
}
)
}
test.Rmd
---
title: "test"
output:
html_document:
df_print: paged
pdf_document: default
params:
region: ''
df_values: ''
editor_options:
chunk_output_type: console'
---
I added in two radioButtons (in ui) with selection for type and class but I am uncertain how to update the report output based on selections. There will be 4 .Rmd files that are a combination of the two selections:
Up and Left
Up and Right
Down and Left
Down and Right
Thanks for your help!

Error: argument "body" is missing, with no default

I am dealing with an issue for several hours, please do not punish me on points. tried pretty much everything was suggested on stack overflow. I use golem library to build up the app, thus please be aware of this aspect. Also, if you want to look on the wider code here is the branch I am working on github:
https://github.com/gabrielburcea/bftb
I put a snippet of the code where the error takes place:
app_server <- function(input, output, session) {
shiny::callModule(mod_tools_server, "tools_path_ui_1")
shiny::callModule(mod_gene_expressions_sign_path_server, "gene_expression_sign_path_ui_1")
shiny::callModule(mod_genomic_server, "genomic_ui_1")
# Your application server logic
}
#' The application User-Interface
#'
#' #param request Internal parameter for `{shiny}`.
#' DO NOT REMOVE.
#' #import shiny
#' #noRd
app_ui <- function(request) {
tagList(
# Leave this function for adding external resources
golem_add_external_resources(),
# Your application UI logic
shinyUI(
navbarPage(
windowTitle = "Page",
title = div(img(src = ".png", height = "30px"), "Toolbox"),
theme = shinythemes::shinytheme("cerulean"),
tabPanel("Toolbox", icon = icon("wrench"),
shinydashboard::dashboardPage(
skin = "black",
header = shinydashboard::dashboardHeader(title = "Toolbox", titleWidth = 300),
shinydashboard::dashboardSidebar(
width = 300 ,
shinydashboard::sidebarMenu(
shinydashboard::menuItem(
"Tools",
tabName = "tools_app",
icon = icon("wrench"),
shinydashboard::menuSubItem(
"Gene Expression/Signature/Pathways",
tabName = "gene_app",
icon = icon("chart-line")
),
shinydashboard::menuSubItem(
"Genomic",
tabName = "genomic_app",
icon = icon("universal-access")
),
)
)
)
),
shinydashboard::dashboardBody(
shinydashboard::tabItems(
shinydashboard::tabItem("tools_app", mod_tools_path_ui("tools_path_ui_1")),
shinydashboard::tabItem("gene_app",mod_gene_expressions_sign_path_ui("gene_expression_sign_path_ui_1")),
shinydashboard::tabItem("genomic_app", mod_genomic_ui("genomic_ui_1"))
}
#' Add external Resources to the Application
#'
#' This function is internally used to add external
#' resources inside the Shiny application.
#'
#' #import shiny
#' #importFrom golem add_resource_path activate_js favicon bundle_resources
#' #noRd
golem_add_external_resources <- function() {
add_resource_path(
"www",
app_sys("app/www")
)
tags$head(
favicon(),
bundle_resources(
path = app_sys("app/www"),
app_title = "bftb"
)
# Add here other external resources
# for example, you can add shinyalert::useShinyalert()
)
}
And I get error such as:
Error: argument "body" is missing, with no default
And with more explanations on the error I get is here:
Error: argument "body" is missing, with no default
Backtrace:
1. bftb::app_ui()
at test-golem-recommended.R:2:2
22. shinydashboard::dashboardPage(...)
23. shinydashboard:::tagAssert(body, type = "div", class = "content-wrapper")
dashboardPage(header, sidebar, body) is missing its body parameter (in your above code dashboardBody isn't called in the right place - note the parenthesis).
Please try the following:
app_server <- function(input, output, session) {
shiny::callModule(mod_tools_server, "tools_path_ui_1")
shiny::callModule(mod_gene_expressions_sign_path_server, "gene_expression_sign_path_ui_1")
shiny::callModule(mod_genomic_server, "genomic_ui_1")
shiny::callModule(mod_epi_server, "epi_ui_1")
shiny::callModule(mod_io_server, "io_ui_1")
shiny::callModule(mod_pharm_server, "pharm_ui_1")
shiny::callModule(mod_cell_server, "cell_ui_1")
shiny::callModule(mod_mouse_server, "mouse_ui_1")
shiny::callModule(mod_hemebase_server, "hemebase_ui_1")
shiny::callModule(mod_multiomics_server, "multiomics_ui_1")
shiny::callModule(mod_other_server, "other_ui_1")
# Your application server logic
}
#' The application User-Interface
#'
#' #param request Internal parameter for `{shiny}`.
#' DO NOT REMOVE.
#' #import shiny
#' #noRd
app_ui <- function(request) {
tagList(
# Leave this function for adding external resources
golem_add_external_resources(),
# Your application UI logic
shinyUI(
navbarPage(
windowTitle = "BFTB Landing Page",
title = div(img(src = "bftb_logo_v8_bare.png", height = "30px"), "AZ Oncology Bioinformatics Toolbox"),
theme = shinythemes::shinytheme("cerulean"),
tabPanel("Toolbox", icon = icon("wrench"),
shinydashboard::dashboardPage(
skin = "black",
header = shinydashboard::dashboardHeader(title = "AZ Oncology Bioinformatics Toolbox", titleWidth = 300),
shinydashboard::dashboardSidebar(
width = 300 ,
shinydashboard::sidebarMenu(
shinydashboard::menuItem(
"Tools",
tabName = "tools_app",
icon = icon("wrench"),
shinydashboard::menuSubItem(
"Gene Expression/Signature/Pathways",
tabName = "gene_app",
icon = icon("chart-line")
),
shinydashboard::menuSubItem(
"Genomic",
tabName = "genomic_app",
icon = icon("universal-access")
),
shinydashboard::menuSubItem(
"Epigenetics",
tabName = "epi_app",
icon = icon("chart-bar")
),
shinydashboard::menuSubItem(
"Immune-oncology",
tabName = "io_app",
icon = icon("heartbeat")
),
shinydashboard::menuSubItem(
"Pharmacology",
tabName = "pharm_app",
icon = icon("plus-square")
),
shinydashboard::menuSubItem(
"Cell line Selection",
tabName = "cell_app",
icon = icon("sellcast")
),
shinydashboard::menuSubItem("Mouse",
tabName = "mouse_app",
icon = icon("paw")),
shinydashboard::menuSubItem(
"Haem Oncology",
tabName = "hemebase_app",
icon = icon("h-square")
),
shinydashboard::menuSubItem("Multiomics",
tabName = "multiomics_app",
icon = icon("list")),
shinydashboard::menuSubItem(
"Other",
tabName = "other_app",
icon = icon("option-horizontal", lib = "glyphicon"))
)
)
),
shinydashboard::dashboardBody(
shinydashboard::tabItems(
shinydashboard::tabItem("tools_app", mod_tools_path_ui("tools_path_ui_1")),
shinydashboard::tabItem("gene_app",mod_gene_expressions_sign_path_ui("gene_expression_sign_path_ui_1")),
shinydashboard::tabItem("genomic_app", mod_genomic_ui("genomic_ui_1")),
shinydashboard::tabItem("epi_app", mod_epi_ui("epi_ui_1")),
shinydashboard::tabItem("io_app", mod_io_ui("io_ui_1")),
shinydashboard::tabItem("pharm_app", mod_pharm_ui("pharm_ui_1")),
shinydashboard::tabItem("cell_app", mod_cell_ui("cell_ui_1")),
shinydashboard::tabItem("mouse_app", mod_mouse_ui("mouse_ui_1")),
shinydashboard::tabItem("hemebase_app", mod_hemebase_ui("hemebase_ui_1")),
shinydashboard::tabItem("multiomics_app", mod_multiomics_ui("multiomics_ui_1")),
shinydashboard::tabItem("other_app", mod_other_ui("other_ui_1"))))
))
)))
}
#' Add external Resources to the Application
#'
#' This function is internally used to add external
#' resources inside the Shiny application.
#'
#' #import shiny
#' #importFrom golem add_resource_path activate_js favicon bundle_resources
#' #noRd
golem_add_external_resources <- function() {
add_resource_path(
"www",
app_sys("app/www")
)
tags$head(
favicon(),
bundle_resources(
path = app_sys("app/www"),
app_title = "bftb"
)
# Add here other external resources
# for example, you can add shinyalert::useShinyalert()
)
}

Can I call a function (not a module) from within shiny modile- can I pass the module reactive values as arguments of function

I am pretty new to Shiny modules.
I am trying to call a function (not a module) from one of my modules.
I would like to pass in the contents of my current reactive values (in my module) as arguments into the function.
The function make a sql query command based on the mrn number, startdate and enddate that is supposed to be fed into the function from 'modemtab'.
this is the error that I get:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
I understand that this is because I'm passing the reactive values not contents of them into the function. My question is how can I pass the contents of these reactive values.
I included a piece of my code here.
Thanks.
app_server <- function(input, output,session) {
.
.
# getting csvupload_values from the first module and feeding it into the next.
csvupload_values <- callModule(csvupload, 'csv-upload')
callModule(modemtab,'mrntab', csvupload_values)
modemtab <- function(input, output, session, csvupload_values){
# the ouput$query is made in the UI part, but it's not the cause of issue.
output$query <- renderText({
if(!is.null(csvupload_values$file_uploaded())){
make_query(mrns = csvupload_values$file_uploaded()$mrns,
startDate = csvupload_values$dates()[1],
endDate = csvupload_values$dates()[2])
}
#This is the function called from within the second module (modemtab)
#this function is saved as a separate file in R folder
make_query <- function(...){
glue_sql("
select *
FROM table
WHERE
rgn_cd = {`rgn_cd`}
AND prdct_lne_cd = {`lob`}
AND ENCTR_STRT_TS >= {`startDate`}
AND ENCTR_END_TS <= {`endDate`}
"
,...
,.con = DBI::ANSI())
}
csvuploadUI <- function(id){
ns <- NS(id)
tagList(
fileInput(ns('file'), "Choose CSV File",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
dateRangeInput(
ns('mrn_date_range'), label = 'Select the range of date:',
start = NULL, end = NULL, min = NULL,
max = NULL, format = "mm/dd/yyyy",
startview = "month", weekstart = 0,
language = "en", separator = " to ", width = NULL),
# Input: Checkbox if file has header ----
checkboxInput(ns('header'), "Header", TRUE)
)
}
# Module Server
csvupload <- function(input, output, session){
userFile <- reactive({
# If no file is selected, don't do anything
validate(need(input$file, message = FALSE))
input$file
})
dataframe <- reactive({
read.csv(userFile()$datapath,
header = input$header)
})
Here:
csvupload_values <- callModule(csvupload, 'csv-upload')
callModule(modemtab,'mrntab', csvupload_values)
csvupload_values is a reactive conductor, so you can't do callModule(modemtab,'mrntab', csvupload_values) outside of a reactive context. You can do:
server <- function(input, output,session) {
csvupload_values <- callModule(csvupload, 'csv-upload')
observeEvent(csvupload_values(),{
if(!is.null(csvupload_values())){
callModule(modemtab, 'mrntab', csvupload_values)
}
})
}
Now, csvupload_values() is a dataframe once you have uploaded the file, so I don't understand why you do csvupload_values$file_uploaded(). Here is a full example:
modemtabUI <- function(id){
ns <- NS(id)
textOutput(ns("query"))
}
modemtab <- function(input, output, session, csvupload_values){
output$query <- renderText({
colnames(csvupload_values())
})
}
csvuploadUI <- function(id){
ns <- NS(id)
tagList(
fileInput(ns('file'), "Choose CSV File",
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
checkboxInput(ns('header'), "Header", TRUE),
dateRangeInput(
ns('mrn_date_range'), label = 'Select the range of date:',
start = NULL, end = NULL, min = NULL, max = NULL, format = "mm/dd/yyyy",
startview = "month", weekstart = 0,
language = "en", separator = " to ", width = NULL)
)
}
csvupload <- function(input, output, session){
userFile <- reactive({
# If no file is selected, don't do anything
validate(need(input$file, message = FALSE))
input$file
})
reactive({
read.csv(userFile()$datapath, header = input$header)
})
}
ui <- fluidPage(
csvuploadUI("csv-upload")
modemtabUI("mrntab")
)
server <- function(input, output,session) {
csvupload_values <- callModule(csvupload, 'csv-upload')
observeEvent(csvupload_values(),{
if(!is.null(csvupload_values())){
callModule(modemtab, 'mrntab', csvupload_values)
}
})
}
shinyApp(ui, server)

Downloading the output from Shiny APP (need some advice)

I want to download the output of this App which I made but there is an error and when I open the downloaded data it is empty.I make a data set by output$other_val_show and I want to download it. Any advice?
The following code in for the UI section.
library(shiny)
library(quantreg)
library(quantregGrowth)
library(plotly)
library(rsconnect)
library(ggplot2)
library(lattice)
ui = tagList(
tags$head(tags$style(HTML("body{ background: aliceblue; }"))),
navbarPage(title="",
tabPanel("Data Import",
sidebarLayout(sidebarPanel( fileInput("file","Upload your CSV",multiple = FALSE),
tags$hr(),
h5(helpText("Select the read.table parameters below")),
checkboxInput(inputId = 'header', label = 'Header', value = FALSE),
checkboxInput(inputId = "stringAsFactors", "StringAsFactors", FALSE),
radioButtons (inputId = 'sep', label = 'Separator',
choices = c(Comma=',',Semicolon=';',Tab='\t', Space=''), selected = ',')
),
mainPanel(uiOutput("tb1"))
)),
tabPanel("Interval",
sidebarLayout(sidebarPanel(
uiOutput("model_select"),
uiOutput("var1_select"),
uiOutput("rest_var_select"),
#uiOutput("testText1"), br(),
#textInput("Smooting Parameter min value", "Smooting Parameter max value", value = "")
sliderInput("range", "Smooth Parameter range:",min = 0, max = 1000, value = c(0,100)),
downloadButton('downloadData', 'Download')
),
mainPanel(helpText("Selected variables and Fitted values"),
verbatimTextOutput("other_val_show")))),
tabPanel("Model Summary", verbatimTextOutput("summary")),
tabPanel("Scatterplot", plotOutput("scatterplot"))#, # Plot
#tabPanel("Distribution", # Plots of distributions
#fluidRow(
#column(6, plotOutput("distribution1")),
#column(6, plotOutput("distribution2")))
#)
,inverse = TRUE,position="static-top",theme ="bootstrap.css"))
The following code in for the Server section. (I want to download the output which is "gr" and I want to download it by downloadHandler function.
server<-function(input,output) {
data <- reactive({
lower <- input$range[1]
upper <- input$range[2]
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)
})
output$table <- renderTable({
if(is.null(data())){return ()}
data()
})
output$tb1 <- renderUI({
tableOutput("table")
})
#output$model_select<-renderUI({
#selectInput("modelselect","Select Algo",choices = c("Reference Interval"="Model"))
#})
output$var1_select<-renderUI({
selectInput("ind_var_select","Select Independent Variable", choices =as.list(names(data())),multiple = FALSE)
})
output$rest_var_select<-renderUI({
checkboxGroupInput("other_var_select","Select Dependent Variable",choices =as.list(names(data()))) #Select other Var
})
output$other_val_show<-renderPrint({
input$other_var_select
input$ind_var_select
f<-data()
lower <- input$range[1]
upper <- input$range[2]
library(caret)
library(quantregGrowth)
dep_vars <- paste0(input$ind_var_select, collapse = "+")
after_tilde <- paste0("ps(", dep_vars, ", lambda = seq(",lower,",",upper,",l=100))")
dyn_string <- paste0(input$other_var_select, " ~ ", after_tilde)
Model<-quantregGrowth::gcrq(as.formula(dyn_string),tau=c(0.025,0.975), data=f)
temp <- data.frame(Model$fitted)
gr <- cbind(f, temp)
print(gr)
})
output$downloadData <- downloadHandler(
write.csv(gr, file, row.names = FALSE)
)
}
shinyApp(ui=ui,server=server)
It's hard to fully answer this without a minimal reproducibile example, but here's what I would try:
Create gr outside of renderPrint
Use gr() in downloadHandler
Rewrite downloadHandler to include content and filename arguments
Here's a minimal example with the same logic as your app, i.e. create a reactive dataframe which is both printed (renderPrint) and downloadable (downloadHandler).
library(shiny)
ui <- navbarPage(title = "Example",
tabPanel("First",
selectInput("fruit", "Fruit", c("apple", "orange", "pear")),
h4("Output from renderPrint:"),
textOutput("other_val_show"),
h4("Download Button: "),
downloadButton("downloadData")))
server <- function(input, output) {
gr <- reactive({
data.frame(fruit = input$fruit)
})
output$other_val_show <- renderPrint({
print(gr())
})
output$downloadData <- downloadHandler(
filename = "example.csv",
content = function(file) {
write.csv(gr(), file)
})
}
shinyApp(ui, server)
You define gr inside the scope of that renderPrint function so it isn't available to downloadHandler. You should define gr as a reactive value somewhere outside that function. That way, when you assign it in the renderPrint function, it will be accessible to the entire scope of your program.
In the future, it would be helpful to provide the text of any error messages you get - they are often quite helpful to solving problems.