Shiny numericInput values initialize NULL

I'm writing a shiny app that creates a new data frame from an existing data frame with an additional column for user inputs. The input objects are all initialized with starting values from a static vector, but I get the following error message:

Warning: Error in data.frame: arguments imply differing number of rows: 3, 0
  118: stop
  117: data.frame
  116: <reactive:new_df> [H:\reprextest/app.R#22]
  100: new_df
   99: renderPrint
   98: func
   82: origRenderFunc
   81: output$df
    1: runApp

The error is thrown by the code below. The renderPrint function call is the parent of the error, but after a second, the output object prints new_df as expected. I believe the issue is that for a split second, R recognizes the numericInput objects as extant, but does not send the object values, leaving the vector containing the inputs with three NULL entries.

How do I prevent this?

library(shiny)


ui <- fluidPage(
    fluidRow(uiOutput("ex1"), uiOutput("ex2"), uiOutput("ex3"), verbatimTextOutput("df"))
)

server <- function(input, output) {
    start_vals <- c(2,4,6)
    
    create_uis <- function(index){
        ui_code <- paste0("ex", index)
        in_code <- paste0("in", index)
        output[[ui_code]] <- renderUI(numericInput(in_code, "Example", value = start_vals[index]))
    }
    
    sapply(1:3, create_uis)
    
    df <- data.frame("COL1" = c(1,2,3), "COL2" = c("a", "b", "c"))
    new_df <- reactive({data.frame(df, "NEWCOL" = c(input$in1, input$in2, input$in3))})
    output$df <- renderPrint(new_df())
}

 
shinyApp(ui = ui, server = server)

Shiny applications not supported in static R Markdown documents

Created on 2020-01-21 by the reprex package (v0.3.0)

Hi @cwill. The problem caused when first evaluate new_df() in renderPrint, the input$in1, input$in2 and input$in3 were not rendered yet. The problem was no harm to your app. But if you want to avoid this, check if the three inputs are available before construct the data frame in the reactive expression as follow.

library(shiny)


ui <- fluidPage(
  fluidRow(uiOutput("ex1"), uiOutput("ex2"), uiOutput("ex3"), verbatimTextOutput("df"))
)

server <- function(input, output) {
  start_vals <- c(2,4,6)
  
  create_uis <- function(index){
    ui_code <- paste0("ex", index)
    in_code <- paste0("in", index)
    output[[ui_code]] <- renderUI(numericInput(in_code, "Example", value = start_vals[index]))
  }
  
  sapply(1:3, create_uis)
  
  df <- data.frame("COL1" = c(1,2,3), "COL2" = c("a", "b", "c"))
  new_df <- reactive({
    req(input$in1, input$in2, input$in3)
    data.frame(df, "NEWCOL" = c(input$in1, input$in2, input$in3))})
  output$df <- renderPrint(new_df())
}


shinyApp(ui = ui, server = server)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.