Object not found error using eventReactive - r

I have this simple Shiny app in which I want the user to choose among four dataframes -- namely df1, df2, df3 and df4 -- the one than will be displayed using DT:dataTableOutput. The problem is I get this error:
Error in dots_list(...) : object 'df_opt' not found
And I do not know why. I thought the error messages was firing because of something related to the input$df_opt argument I previously had in eventReactive, but then I removed it by adding a button input. Nevertheless, I keep getting the same error message
Does anyone understand why I'm getting this message?
This is a reproducible example of my app:
library(shiny)
library(DT)
choices_df <- c("opt1", "opt2", "opt3", "opt4")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = df_opt,
label = "Choose a database",
choices = df_choices,
selected = choices_df[1] ),
actionButton(
inputId = df_button,
label = "")
),
mainPanel(
DT::dataTableOutput("base_p1")
)
))
server <- function(input, output) {
df_selected <- eventReactive(
input$df_button, {
if( input$df_opt == choices_df[1] ){
df1
}
if( input$df_opt == choices_df[2] ){
df2
}
if( input$df_opt == choices_df[3] ){
df3
}
if( input$df_opt == choices_df[4] ){
df4
}
})
output$base_p1 <- DT::renderDataTable( df_selected(), filter = "top")
}
shinyApp(ui = ui, server = server)

Here is a working version of what you want to do, but with reactiveValues. So basically I find it better to create like an empty holder for reactive variable, then just assign the wanted df to it when user changes input. Code:
library(shiny)
library(DT)
df_choices <- c("opt1", "opt2", "opt3", "opt4")
df1 <- matrix(rnorm(100,10,10),10,10)
df2 <- matrix(rnorm(100,100,10),10,10)
df3 <- matrix(rnorm(100,1099,10),10,10)
df4 <- matrix(rnorm(100,100000,10),10,10)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "df_opt",
label = "Choose a database",
choices = df_choices,
selected = choices_df[1] ),
actionButton(
inputId = "df_button",
label = "click to show")
),
mainPanel(
DT::dataTableOutput("base_p1")
)
))
server <- function(input, output) {
df <- reactiveValues(df=df1)
observeEvent(input$df_button,{
if( input$df_opt == choices_df[1] ){
df$df <- df1
}
if( input$df_opt == choices_df[2] ){
df$df <-df2
}
if( input$df_opt == choices_df[3] ){
df$df <- df3
}
if( input$df_opt == choices_df[4] ){
df$df <- df4
}
})
output$base_p1 <- DT::renderDataTable( df$df, filter = "top")
}
shinyApp(ui = ui, server = server)
EDIT: And yes, inputID should be strings, so "df_opt" and "df_button".

Related

How to add a spinner before a selectizeInput has loaded all the choices? [Shiny]

I want to make an app with 2 actionButtons: 1) to submit the changes before loading a selectizeInput and 2) to draw the plot.
I know how to add a spinner after clicking a actionButton but the majority of the cases is added when you want to show the plot.
However, is it possible to add a spinner without showing any plot?
In this particular case, I want to show a spinner after clicking "Submit" until the selectizeInput from the 'Selection tab' is loaded. As you can see the example that I attach, it takes a bit to load all the choices (since the file has 25000 rows).
I already have one spinner after clicking the second actionButton (Show the plot) but I need one more.
I have created an example, but for some reason the plot is not shown in the shiny app and it appears in the window from R (I don't know why but I added the plot just to show you how I put the second spinner. I want a similar one but with the first actionButton.).
library(shiny)
library(shinycssloaders)
ui <- fluidPage(
titlePanel("My app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Submit",
checkboxInput("log2", "Log2 transformation", value = FALSE),
actionButton("submit", "Submit")
),
tabPanel("Selection",
br(),
selectizeInput(inputId = "numbers", label = "Choose one number:", choices=character(0)),
actionButton("show_plot", "Show the plot")
))
),
mainPanel(
conditionalPanel(
condition = "input.show_plot > 0",
style = "display: none;",
withSpinner( plotOutput("hist"),
type = 5, color = "#0dc5c1", size = 1))
)
)
)
server <- function(input, output, session) {
data <- reactive({
data = read.csv("https://people.sc.fsu.edu/~jburkardt/data/csv/hw_25000.csv")
data[,1] <- as.character(data[,1])
if(input$log2 == TRUE){
cols <- sapply(data, is.numeric)
data[cols] <- lapply(data[cols], function(x) log2(x+1))
}
return(data)
})
mylist <- reactive({
req(data())
data <- data()
data <- data[,1]
return(data)
})
# This is to generate the choices (gene list) depending on the user's input.
observeEvent(input$submit, {
updateSelectizeInput(
session = session,
inputId = "numbers",
choices = mylist(), options=list(maxOptions = length(mylist()))
)
})
v <- reactiveValues()
observeEvent(input$show_plot, {
data <- data()
v$plot <- plot(x=data[,1], y=data[,2])
})
# If the user didn't choose to see the plot, it won't appear.
output$hist <- renderPlot({
req(data())
if (is.null(v$plot)) return()
if(input$show_plot > 0){
v$plot
}
})
}
Does anyone know how to help me, please?
Thanks very much
It's a little tricky.
First of all I'd update the selectizeInput on the server side as the warning suggests:
Warning: The select input "numbers" contains a large number of
options; consider using server-side selectize for massively improved
performance. See the Details section of the ?selectizeInput help
topic.
Furthermore I switched to ggplot2 regarding the plotOutput - Please see this related post.
To show the spinner while the selectizeInput is updating choices we'll need to know how long the update takes. This information can be gathered via shiny's JS events - please also see this article.
Finally, we can show the spinner for a non-existent output, so we are able to control for how long the spinner is shown (see uiOutput("dummyid")):
library(shiny)
library(shinycssloaders)
library(ggplot2)
ui <- fluidPage(
titlePanel("My app"),
tags$script(HTML(
"
$(document).on('shiny:inputchanged', function(event) {
if (event.target.id === 'numbers') {
Shiny.setInputValue('selectizeupdate', true, {priority: 'event'});
}
});
$(document).on('shiny:updateinput', function(event) {
if (event.target.id === 'numbers') {
Shiny.setInputValue('selectizeupdate', false, {priority: 'event'});
}
});
"
)),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Submit",
checkboxInput("log2", "Log2 transformation", value = FALSE),
actionButton("submit", "Submit")
),
tabPanel("Selection",
br(),
selectizeInput(inputId = "numbers", label = "Choose one number:", choices=NULL),
actionButton("show_plot", "Show the plot")
))
),
mainPanel(
uiOutput("plotProxy")
)
)
)
server <- function(input, output, session) {
previousEvent <- reactiveVal(FALSE)
choicesReady <- reactiveVal(FALSE)
submittingData <- reactiveVal(FALSE)
observeEvent(input$selectizeupdate, {
if(previousEvent() && input$selectizeupdate){
choicesReady(TRUE)
submittingData(FALSE)
} else {
choicesReady(FALSE)
}
previousEvent(input$selectizeupdate)
})
data <- reactive({
data = read.csv("https://people.sc.fsu.edu/~jburkardt/data/csv/hw_25000.csv")
if(input$log2 == TRUE){
cols <- sapply(data, is.numeric)
data[cols] <- lapply(data[cols], function(x) log2(x+1))
}
return(data)
})
mylist <- reactive({
req(data()[,1])
})
observeEvent(input$submit, {
submittingData(TRUE)
reactivePlotObject(NULL) # reset
updateSelectizeInput(
session = session,
inputId = "numbers",
choices = mylist(), options=list(maxOptions = length(mylist())),
server = TRUE
)
})
reactivePlotObject <- reactiveVal(NULL)
observeEvent(input$show_plot, {
reactivePlotObject(ggplot(data(), aes_string(x = names(data())[1], y = names(data())[2])) + geom_point())
})
output$hist <- renderPlot({
reactivePlotObject()
})
output$plotProxy <- renderUI({
if(submittingData() && !choicesReady()){
withSpinner(uiOutput("dummyid"), type = 5, color = "#0dc5c1", size = 1)
} else {
conditionalPanel(condition = "input.show_plot > 0", withSpinner(plotOutput("hist"), type = 5, color = "#0dc5c1", size = 1), style = "display: none;")
}
})
}
shinyApp(ui, server)
First 100 rows of your example data (dput(head(data, 100)) - your link might be offline some day):
structure(list(Index = 1:100, Height.Inches. = c(65.78331, 71.51521,
69.39874, 68.2166, 67.78781, 68.69784, 69.80204, 70.01472, 67.90265,
66.78236, 66.48769, 67.62333, 68.30248, 67.11656, 68.27967, 71.0916,
66.461, 68.64927, 71.23033, 67.13118, 67.83379, 68.87881, 63.48115,
68.42187, 67.62804, 67.20864, 70.84235, 67.49434, 66.53401, 65.44098,
69.5233, 65.8132, 67.8163, 70.59505, 71.80484, 69.20613, 66.80368,
67.65893, 67.80701, 64.04535, 68.57463, 65.18357, 69.65814, 67.96731,
65.98088, 68.67249, 66.88088, 67.69868, 69.82117, 69.08817, 69.91479,
67.33182, 70.26939, 69.10344, 65.38356, 70.18447, 70.40617, 66.54376,
66.36418, 67.537, 66.50418, 68.99958, 68.30355, 67.01255, 70.80592,
68.21951, 69.05914, 67.73103, 67.21568, 67.36763, 65.27033, 70.84278,
69.92442, 64.28508, 68.2452, 66.35708, 68.36275, 65.4769, 69.71947,
67.72554, 68.63941, 66.78405, 70.05147, 66.27848, 69.20198, 69.13481,
67.36436, 70.09297, 70.1766, 68.22556, 68.12932, 70.24256, 71.48752,
69.20477, 70.06306, 70.55703, 66.28644, 63.42577, 66.76711, 68.88741
), Weight.Pounds. = c(112.9925, 136.4873, 153.0269, 142.3354,
144.2971, 123.3024, 141.4947, 136.4623, 112.3723, 120.6672, 127.4516,
114.143, 125.6107, 122.4618, 116.0866, 139.9975, 129.5023, 142.9733,
137.9025, 124.0449, 141.2807, 143.5392, 97.90191, 129.5027, 141.8501,
129.7244, 142.4235, 131.5502, 108.3324, 113.8922, 103.3016, 120.7536,
125.7886, 136.2225, 140.1015, 128.7487, 141.7994, 121.2319, 131.3478,
106.7115, 124.3598, 124.8591, 139.6711, 137.3696, 106.4499, 128.7639,
145.6837, 116.819, 143.6215, 134.9325, 147.0219, 126.3285, 125.4839,
115.7084, 123.4892, 147.8926, 155.8987, 128.0742, 119.3701, 133.8148,
128.7325, 137.5453, 129.7604, 128.824, 135.3165, 109.6113, 142.4684,
132.749, 103.5275, 124.7299, 129.3137, 134.0175, 140.3969, 102.8351,
128.5214, 120.2991, 138.6036, 132.9574, 115.6233, 122.524, 134.6254,
121.8986, 155.3767, 128.9418, 129.1013, 139.4733, 140.8901, 131.5916,
121.1232, 131.5127, 136.5479, 141.4896, 140.6104, 112.1413, 133.457,
131.8001, 120.0285, 123.0972, 128.1432, 115.4759)), row.names = c(NA,
100L), class = "data.frame")

How to dynamically change the values of inputs based on data from a reactive environment?

Given the following shiny code:
library(shiny)
library(data.table)
df_fr<-data.table(x1=c("a","a","a","b","b","b"),x2=c("1","1","2","2","2","3"))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("x1", "x1", unique(df_fr$x1),multiple=T),
selectInput("x1", "x1", unique(df_fr$x2),multiple=T)
),
mainPanel( plotOutput("plot1") )
)
)
server <- function(input, output,session) {
selectedData <- reactive({
selInputs<-list(input$x1,input$x2)
req( any( !sapply(selInputs,is.null) ) | any(sapply(selInputs,is.null)) )
df_fr[(if( is.null(input$x1) ) {T} else {x1 %in% input$x1})
& (if( is.null(input$x2) ) {T} else {x2 %in% input$x2})
]
})
output$plot1 <- renderPlot({
plot(table(selectedData()))
})
}
shinyApp(ui = ui, server = server)
I want that if I choose option 'a' for 'x1' that only '1' and '2' show up as possible options for 'x2'.
The other way arround, I choose '3' for 'x2' I want that programm shows only 'b' as possible options for 'x1'. So, changing one input should restrict all other inputs to the values that are defined in the data table. Is that possible? If yes, how? I tried already an observed-block which accesses selectedData(). This did not work, unfortunatly.
Thank you! I hope my question is clear.
one way to do it is to use updateSelectInput(). Try this
library(shiny)
library(data.table)
library(ggplot2)
df_fr<-data.table(x1=c("a","a","a","b","b","b"),x2=c("1","1","2","2","2","3"))
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("x1", "x1", unique(df_fr$x1),selected=NULL, multiple=T),
selectInput("x2", "x2", unique(df_fr$x2),selected=NULL, multiple=T)
),
mainPanel( plotOutput("plot1") )
)
)
server <- function(input, output,session) {
DF <- reactiveValues(data1 = NULL,
data2 = NULL)
observe({
if (is.null(input$x1)) {
DF$data1 <- df_fr
}else DF$data1 <- df_fr[x1 %in% input$x1,]
if (is.null(input$x2)) {
DF$data2 <- df_fr
}else DF$data2 <- df_fr[x2 %in% input$x2,]
if (is.null(input$x2)){
if (is.null(input$x1)) {
updateSelectInput(session, inputId="x2", choices=unique(df_fr$x2))
}else updateSelectInput(session, inputId="x2", choices=unique(DF$data1$x2))
}
if (is.null(input$x1)){
if (is.null(input$x2)) {
updateSelectInput(session, inputId="x1", choices=unique(df_fr$x1))
}else updateSelectInput(session, inputId="x1", choices=unique(DF$data2$x1))
}
})
selectedData <- reactive({
req(input$x1,input$x2)
df_fr[(x2 %in% input$x2) & (x1 %in% input$x1),]
})
output$plot1 <- renderPlot({
req(selectedData())
ggplot(selectedData(), aes(x=x1,y=x2)) + geom_point()
})
}
shinyApp(ui = ui, server = server)

Got 'argument 1 is empty error' with selectInput in shinydashboard

I have a shiny app like below using diamonds dataset as an example. I'm using two selectInput as data filter. The first one select a variable. The second one shows the values, depending on the variable selected in the first selectInput. After selection, click the actionButton to trigger the filter. Without any variable and value selected, I want it output the whole dataset.
What I found is after I clear the two selectInput and then click the actionButton, I got error: argument 1 is empty. I do not understand why that happens. Spent hours but unable to find the solution. Do anyone know how I can fix it? Thanks a lot!
library(shiny)
library(shinydashboard)
library(dplyr)
library(rlang)
data(diamonds)
df = diamonds[1:1000,]
subset_data = function(data,
var=NULL,
value=NULL){
if (!is.null(var)) {
if(!is.null(value)) {
data = data %>% filter(!!sym(var) == value)
}
}
return(data)
}
ui <- dashboardPage(
dashboardHeader(title = "example"),
dashboardSidebar(),
dashboardBody(
fluidRow(
selectizeInput(inputId = 'var',
label='Select variable',
choices = c('cut', 'color'),
multiple=FALSE,
options = list(
maxItems = 1,
placeholder = '',
onInitialize = I("function() { this.setValue(''); }"))),
uiOutput("valueUI"),
actionButton('go', 'apply filter'),
tableOutput('table')
)
)
)
server <- function(input, output, session) {
output$valueUI = renderUI({
if (input$var == '') {
vals = ''
}
if (input$var == 'cut') {
vals = c('Premium', 'Good', 'Very Good', 'Fair')
}
if (input$var == 'color'){
vals = c('E', 'J', 'I', 'H')
}
selectizeInput(inputId = 'value',
label='Select values',
choices = c('',vals),
multiple=FALSE,
options = list(
maxItems = 1,
placeholder = '',
onInitialize = I("function() { this.setValue(''); }")))
})
dat = reactive({
input$go
isolate( subset_data(data=df, var=input$var, value=input$value) )
})
output$table <- renderTable({
dat()
})
}
shinyApp(ui, server)
if input$var not given, it will be handled with '' as you implemented.
However, in same time it will also give parameter var value in subset_data function as '' not NULL, so it will be not recognized with !is.null(var) and trigger filter for data .
You can see these explanation if you change subset_data like below code;
subset_data = function(data,
var=NULL,
value=NULL){
print('var:')
print(var) # var is given as ''
print("value:")
print(value)
if (!is.null(var)) {
if(!is.null(value)) {
print('hi')
data = data %>% filter(!!sym(var) == value)
print('hi2') # this will not printed, since filter makes error.
}
}
return(data)
}
so in this case, you can fix them with adding just 1 line on subset_data to check if var == ''.
if( var == '' ) return(data)
Regards.

Shiny R: Modifying the variable class

I am trying to create a shiny-app that load data-set, present the variable list and their classes and allow the user to modify the class of a selected variable. All the functions in the following code are working except to the last function in the server- observeEvent which not working when trying to modify the variable class. Any suggestions?
Thank you in advance,
Rami
`
rm(list = ls())
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(title = "Shiny Example"),
#--------------------------------------------------------------------
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "data", icon = icon("th"))
)
),
#--------------------------------------------------------------------
dashboardBody(
#--------------------------------------------------------------------
tabItem(tabName = "data",
fluidPage(
fluidRow(
box(
selectInput('dataset', 'Select Dataset', list(GermanCredit = "GermanCredit",
cars = "cars",
iris = "iris")),
title = "Datasets",width = 4, status = "primary",
checkboxInput("select_all", "Select All Variable", value = TRUE),
conditionalPanel(condition = "input.select_all == false",
uiOutput("show.var"))
),
box(
title = "Variable Summary", width = 4, status = "primary",
DT::dataTableOutput('summary.data')
),
box(
title = "Modify the Variable Class", width = 4, status = "primary",
radioButtons("choose_class", label = "Modify the Variable Class",
choices = list(Numeric = "numeric", Factor = "factor",
Character = "character"),
selected = "numeric"),
actionButton("var_modify", "Modify")
)
)
)
)
)
)
#--------------------------------------------------------------------
# Server Function
#--------------------------------------------------------------------
server <- function(input, output,session) {
#--------------------------------------------------------------------
# loading the data
get.df <- reactive({
if(input$dataset == "GermanCredit"){
data("GermanCredit")
GermanCredit
}else if(input$dataset == "cars"){
data(cars)
cars
}else if(input$dataset == "iris"){
data("iris")
iris
}
})
# Getting the list of variable from the loaded dataset
var_list <- reactive(names(get.df()))
# Choosing the variable - checkbox option
output$show.var <- renderUI({
checkboxGroupInput('show_var', 'Select Variables', var_list(), selected = var_list())
})
# Setting the data frame based on the variable selction
df <- reactive({
if(input$select_all){
df <- get.df()
} else if(!input$select_all){
df <- get.df()[, input$show_var, drop = FALSE]
}
return(df)
})
# create list of variables
col.name <- reactive({
d <- data.frame(names(df()), sapply(df(),class))
names(d) <- c("Name", "Class")
return(d)
})
# render the variable list into table
output$summary.data <- DT::renderDataTable(col.name(), server = FALSE, rownames = FALSE,
selection = list(selected = 1, mode = 'single'),
options = list(lengthMenu = c(5, 10, 15, 20), pageLength = 20, dom = 'p'))
# storing the selected variable from the variables list table
table.sel <- reactive({
df()[,which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])]
})
# Trying to modify the variable class
observeEvent(input$var_modify,{
modify.row <- which(colnames(df()) == col.name()[input$summary.data_rows_selected,1])
if( input$choose_class == "numeric"){
df()[, modify.row] <- as.numeric(df()[, modify.row])
} else if( input$choose_class == "factor"){
df()[, modify.row] <- as.factor(df()[, modify.row])
} else if( input$choose_class == "character"){
df()[, modify.row] <- as.character(df()[, modify.row])
}
})
}
shinyApp(ui = ui, server = server)
`
I would use reactiveValues() instead.
library(shiny)
# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("classType", "Class Type:", c("as.numeric", "as.character"))
),
mainPanel(
textOutput("class")
)
)
))
server <- shinyServer(function(input, output) {
global <- reactiveValues(sample = 1:9)
observe({
global$sample <- get(input$classType)(global$sample)
})
output$class <- renderText({
print(class(global$sample))
})
})
shinyApp(ui = ui, server = server)
In case you are interested:
Concerning your attempt: reactive() is a function and you called the output of the function by df()[, modify.row]. So in your code you try to change the output of the function, but that does not change the output of futures calls of that function.
Maybe it is easier to see in a simplified version:
mean(1:3) <- 1
The code can not change the mean function to output 1 in future. So thats what reactiveValues() help with :). Hope that helps!

Shiny Data table display all data using filter

I can create a data table in shiny that shows data for any individual buffalo but I can't figure out how to display all buffalo data at the same time. Any help is appreciated.
Sample Data:
cleanbuffalo <- data.frame(name = c("queen","toni","pepper"),
longitude = c(31.8,32,33),
latitude = c(-24,-25,-26))
Shiny UI:
shinyUI(navbarPage("Buffalo Migration", id ="nav",
tabPanel("Data",
fluidRow(
column(3,
selectInput("allnamesbuffalo", "Buffalo", c("All Buffalo" = "all buffalo", vars))
)
),
hr(),
DT::dataTableOutput("buffalotable")
)
)
)
Shiny Server:
shinyServer(function(input, output, session) {
observe({
allnamesbuffalo <- if (is.null(input$allnamesbuffalo)) character(0) else {
filter(cleanbuffalo, name %in% input$allnamesbuffalo) %>%
`$`('name') %>%
unique() %>%
sort()
}
})
output$buffalotable <- DT::renderDataTable({
df <- cleanbuffalo %>%
filter(
cleanbuffalo$name == input$allnamesbuffalo,
is.null(input$allnamesbuffalo) | name %in% cleanbuffalo$name
)
action <- DT::dataTableAjax(session,df)
DT::datatable(df, options = list(ajax = list(url = action)),
escape = FALSE)
})
})
Here is a working example. Note that I added stringsAsFactors=F in your data frame, otherwise you need to use levels(cleanbuffalo$name) to get the names.
library(shiny)
library(dplyr)
cleanbuffalo <- data.frame(name = c("queen","toni","pepper"),
longitude = c(31.8,32,33),
latitude = c(-24,-25,-26), stringsAsFactors = F)
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("allnamesbuffalo", "Buffalo", c("all", cleanbuffalo$name))
),
mainPanel(
dataTableOutput("buffalotable")
)
)
))
server <- shinyServer(function(input, output, session) {
output$buffalotable <- renderDataTable({
names <- NULL
if (input$allnamesbuffalo == "all") {
names <- cleanbuffalo$name
} else {
names <- input$allnamesbuffalo
}
filter(cleanbuffalo, name %in% names)
})
})
shinyApp(ui = ui, server = server)

Resources