'How to assign global variables that can be accessed by other output$function in R shiny?
So I'm creating an R shiny app where I need to upload a few files and operate on them to output some (let's say 3) plots. So in every renderPlot() function in server I need to repeat the operations for it to work (code is chunky now). I was wondering if there's any way to assign the ingested file and operations to a global variable and access it in every renderplot() function? Is there a way to actually access it outside the server() at all (I've been told no)?
In other threads, I was told to use reactive() or reactiveValues() but to no avail. Below is the sample code:
sample2 <- as.data.frame(matrix(rnorm(10*100, 1, .5), ncol=10))
write.csv(sample, "sample.csv") #Creating sample csv to be ingested in R shiny
ui <- fluidPage(
headerPanel("Webpapp"),
sidebarPanel(
fileInput(inputId = "filedata", #Upload sample.csv here
label = "Upload the Raw Data File",
accept = c("text/csv", "text/comma-separated-values,text/plain",
".csv")),
selectInput("title", "Select title:", choices = list("hi", "hello"), selected = "Hi"),
),
mainPanel(plotOutput('plot')),
mainPanel(plotOutput('normalized_plot')),
mainPanel(plotOutput('advanced_normalized_plot'))
)
server <- function(session, input, output) { #original code I have needs session
data <- reactive({
req(input$filedata)
read.csv(input$filedata$datapath, header = T)
})
normalized <- reactive({
#I want to assign these objects as a global variable which can be use by other output functions
df <- data()
normalizd_df <- df + 1.5
colnames(normalizd_df) <- paste(input$title,rep(1:10)) #I do need to use input in this reactive function
advanced_normalized <- normalized_df * 15.454
})
output$plot <- renderPlot({
#This works but I do not want to do this every output function
sample_d <- data()
plot(density(sample_d[,1]), main = input$title)
})
output$normalized_plot <- renderPlot({ #Does not work
plot(density(normalized$normalizd_df[,1]), main = input$title)
})
output$advanced_normalized_plot <- renderPlot({
sample_a <- advanced_normalized - normalized_df #This doesn't work
plot(density(normalized$advanced_normalized[,1]), main = input$title)
})
}
shinyApp(ui = ui, server = server)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
