I am working on a small Shiny R app which includes some reactive functions, but I found its behavior is not what I expected. In my app:
1. A user uploads a CSV file and select columns and studies (rows) to display
2. In this reactive process, I called a function `test_func`, which prints the number of rows selected. However, I found for a single uploaded file, this `test_func` is called twice, and the first outcome is always `0`. I am wondering how to only call this function once, since the first `0` breaks my app... Thanks!
`> shiny::runApp('my app')`
`>Listening on http://127.0.0.1:3368`
`[1] 0`
`[1] 15`
Below is my code:
###ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel('test'),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
checkboxGroupInput('show_vars', 'Columns to show:',
choices=c("Col1"="Col1", "Col2"="Col2", "Col3"="Col3"),
c("Col1"="Col1", "Col2"="Col2", "Col3"="Col3")),
uiOutput("study")
),
mainPanel(
dataTableOutput('contents')
)
)
))
##server.R
test_func<-function(data_raw){
print (nrow(data_raw))
}
shinyServer(function(input, output) {
dataInput <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
data_load_all<-read.csv(inFile$datapath, header=T, sep=',', quote='"', stringsAsFactors=FALSE)
data_load<-subset(data_load_all, select=c(input$show_vars))
data_study<-unique(data_load$Col2)
return (list("data_load_all"=data_load_all, "data_load"=data_load, "data_study"=data_study))
})
study<-reactive({
if (is.null(dataInput()$data_study))
return ()
all_citation<-dataInput()$data_load$Col2
study_choose<-unlist(lapply(input$columns, function(x) which(all_citation==x)))
test<-test_func(dataInput()$data_load_all[study_choose, ])
return (list("study_choose"=study_choose))
})
output$contents <- renderDataTable({
study_choose_temp<-study()$study_choose
dataInput()$data_load[study_choose_temp,]
}
)
output$study <- renderUI({
# If missing input, return to avoid error later in function
if(is.null(dataInput()$data_study)) return()
# Create the checkboxes and select them all by default
checkboxGroupInput("columns", "Choose studies to plot",
choices = dataInput()$data_study,
selected = dataInput()$data_study)
})
###[CSV][1]