How can I pass data between functions in a Shiny app
Use data()$count
. The ()
is how you retrieve a reactive function's value, and the fact that you can see data
from within the two reactive plot functions is just a natural consequence of R's scoping rules.
Shiny app modules: How to pass variables defined in the Server as arguments of functions in the UI?
As suggested by Stéphane's comment above, using renderUI()
allows to pass variables available in the server to arguments of functions used normally at the UI. So replacing mod_table_ui()
and mod_table_server()
from the code above with the functions below will do the job:
mod_table_ui <- function(id) {
ns <- NS(id)
tagList(
textOutput(ns("text")),
uiOutput(ns('renderUIway')),
tableOutput(ns("table"))
)
}
mod_table_server <- function(id, r6) {
moduleServer(id, function(input, output, session) {
observeEvent(gargoyle::watch("update_iris"), {
output$text <- renderText(paste("Multiplier:", r6$multiplier))
output$table <- renderTable({
req(!is.null(r6$res_data))
r6$res_data
})
output$renderUIway <- renderUI({
tagList(
###### This now also works! ######
shinydashboard::valueBox(
value = r6$n_rows,
subtitle = "nr of rows"
)
###############################
###### This works: ######
# shinydashboard::valueBox(
# value = rnorm(1),
# subtitle = "random nr"
# )
#########################
)
})
})
})
}
How to pass values from ui to server in a shiny module
One way to do it is to use a hidden selectInput
with all the choices selected. Shinyjs
package is required. Try this
library(shiny)
library(shinyjs)
rotatingRadioInput <- function(id, label, choices = c('A' = 'a', 'B' = 'b'), selected = 'a') {
labelNames <- names(choices)
values <- unname(choices)
tagList(
radioButtons(NS(id, "radio"),
label = NULL,
choiceValues = values,
choiceNames = labelNames,
selected = selected
),
actionButton(NS(id, 'rotate'), 'rotate'),
hidden(selectInput(NS(id,"mychoices"),"", choices=values, selected=values, multiple=TRUE))
)
}
rotatingRadioServer <- function(id) {
moduleServer(id, function(input, output, session) {
observeEvent(input$rotate, {
choices <- input$mychoices
newchoices <- choices[!(choices %in% input$radio)]
updateRadioButtons(session, "radio", selected = newchoices[1])
})
reactive({input$radio})
# return(reactive({input$radio}))
})
}
#rotatingRadioApp <- function() {
ui <- fluidPage(
useShinyjs(),
rotatingRadioInput("rotate"),
textOutput("value")
)
server <- function(input, output, server) {
rotatingValue <- rotatingRadioServer("rotate")
#observe({print(rotatingValue())})
output$value <- renderText(paste0("Selected: ", rotatingValue()))
}
shinyApp(ui, server)
#}
#rotatingRadioApp()
R Shiny problem to pass reactive input to another function after plotting
The problem is that you call the columns x
and y
in your function AOC
but these columns are only defined in your renderPlot
, not in the whole server.
Replacing x
and y
by input$xcol
and input$ycol
(and using [[ ]]
) allows to compute the area under the curve.
Corrected example below:
library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(DescTools)
library(pROC)
library(shinythemes)
ui <- shinyUI(fluidPage(
titlePanel("Column Plot"),
tabsetPanel(
tabPanel("Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
tags$br(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
';'),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"')
),
mainPanel(
tableOutput('contents')
)
)
),
tabPanel("Plot",
pageWithSidebar(
headerPanel('My Plot'),
sidebarPanel(
# "Empty inputs" - they will be updated after the data is uploaded
selectInput("xcol", "X Variable", ""),
selectInput("ycol", "Y Variable", "", selected = "")
),
mainPanel(
plotOutput("MyPlot")
)
),
######
h4("Area under curve"),
textOutput("AUC")
)
)
)
)
server <- shinyServer(function(input, output, session) {
# added "session" because updateSelectInput requires it
data <- reactive({
req(input$file1) ## ?req # require that the input is available
inFile <- input$file1
df <- read.csv(inFile$datapath, header = input$header, sep = input$sep,
quote = input$quote)
# Update inputs (you could create an observer with both updateSel...)
updateSelectInput(session, inputId = "xcol", label = "X Variable",
choices = names(df), selected = names(df))
updateSelectInput(session, inputId = "ycol", label = "Y Variable",
choices = names(df), selected = names(df)[2])
return(df)
})
output$contents <- renderTable({
data()
})
output$MyPlot <- renderPlot({
x <- req(input$xcol)
y <- req(input$ycol)
p <- ggplot(data(), aes_string(x = x, y = y)) + geom_point(color="blue", size =7)
plot(p)
############
# Here is the problem, I can not pass x and y to the AUC function to calculate area under curve
# for the user input
output$AUC <- renderText({
AUC(data()[[input$xcol]], data()[[input$ycol]], method ="spline")
})
#######################
})
})
shinyApp(ui, server)
Edit: you may have an error
Error: maximum number of subdivisions reached
but I suppose this is due to the function AOC
.
Passing argument to a function in shiny R
take out the
deparse
andsubstitute
from yoursprintf
command, and add single quotes around the value you want to match in the SQL statement you're generatingget rid of the
get
function because you're not trying to "get" an object
for example....
library(shiny)
library(networkD3)
library(DT)
library(sqldf)
df <- read.csv(header = T, text = '
source,name,age,hair
dad,Jon X,18,brown
dad,Jon Y,22,blonde
')
funct <-
function (n) {
isp <- sprintf("Select df.age From df Where df.name='%s';", n)
isd <- sqldf::sqldf(isp)
return(isd)
}
ui <- shinyUI(fluidPage(
fluidRow(
column(4, simpleNetworkOutput("simple")),
column(4, DT::dataTableOutput("table"))
)
))
server <- shinyServer(function(input, output, session) {
session$onSessionEnded(stopApp)
output$simple <- renderSimpleNetwork({
sn<-simpleNetwork(df)
sn$x$options$clickAction = 'Shiny.onInputChange("id",d.name)'
sn
})
output$table <- DT::renderDataTable(DT::datatable(funct(input$id)))
})
shinyApp(ui = ui, server = server)
however, if all you want is to display a value associated with a given selection, I highly suggest drastically reducing the complexity to something like this
library(shiny)
library(networkD3)
df <- read.csv(header = T, text = '
source,name,age,hair
dad,Jon X,18,brown
dad,Jon Y,22,blonde
')
ui <- shinyUI(fluidPage(
fluidRow(
column(4, simpleNetworkOutput("simple")),
column(4, textOutput("text"))
)
))
server <- shinyServer(function(input, output, session) {
session$onSessionEnded(stopApp)
output$simple <- renderSimpleNetwork({
sn <- simpleNetwork(df)
sn$x$options$clickAction <- 'Shiny.onInputChange("id", d.name)'
sn
})
output$text <- renderPrint({ df$age[df$name == input$id] })
})
shinyApp(ui = ui, server = server)
How to pass an Input inside a max() function in R studio (shiny App)?
Input values are only available inside the app server. More properly, they need reactive contexts provided by observe/reactive.
Try this instead:
Note: I used iris
dataset as dummy data to make the code reproducible.
library(shiny)
library(tidyverse)
ui <- basicPage(
selectInput(
inputId = "sel",
label = "eine möglichkeit auswählen",
choices = names(iris)
),
# list("vaccinationsTotal","peopleFirstTotal","peopleFullTotal","peopleBoosterTotal")),
plotOutput("plot")
)
server <- function(input, output, session) {
# Summarize Data and then Plot
data <- reactive({
req(input$sel)
df <- iris %>%
group_by(Species) %>%
summarise(output = max(get(input$sel)))
print(df)
df
})
# Plot
output$plot <- renderPlot({
g <- ggplot(data(), aes(y = output, x = Species))
g + geom_bar(stat = "sum")
})
}
shinyApp(ui, server)
Related Topics
Clear Memory Allocated by R Session (Gc() Doesnt Help !)
Saving a Data Frame as a Binary File
Extract Survival Probabilities in Survfit by Groups
How to Show Corpus Text in R Tm Package
S4 Classes: Multiple Types Per Slot
Stacke Different Plots in a Facet Manner
Provide Shades Between Dates on X Axis
How to Change Strip.Text Labels in Ggplot with Facet and Margin=True
Change Paper Size and Orientation in an Rmarkdown PDF
How to Convert by the Minute Data to Hourly Average Data
How to Summarizing Data Statistics Using R
Handling Latex Backslashes in Xtable
Shading Confidence Intervals Manually with Ggplot2
Taking a Disproportionate Sample from a Dataset in R