Search code examples
rshiny-servershiny

server.R undefined columns?


I'm trying to create a R Shiny app and have encountered the error:

Error in `[.data.frame`(dataset.temp, , input$col) : 
  undefined columns selected

I'm not sure what's causing this, hopefully someone could help me figure it out. Here's a sample code:

ui.R

shinyUI(fluidPage(
  titlePanel("Data"),
  sidebarLayout(
    sidebarPanel(
      textInput("from","Missing",
                value="Enter characters"),
      textInput("to","Missing",
                value="Enter characters"),
      selectInput("col","Select Column",
                  choices = c(1:6),
                  selected=1)),
    mainPanel(
      tableOutput('contents')
    )
  )
))

server.R

library(DT)
file <- read.csv("file.csv")
shinyServer(function(input, output) {
dataset.temp <- file
output$contents <- renderTable({
dataset.temp[,input$col] <- gsub(input$from,input$to,dataset.temp[,input$col])
    dataset.temp
  })
})

Any thoughts?


Solution

  • I got a different error from running your code:

    Error in `[.data.frame`(dataset.temp, , input$col) : 
      undefined columns selected
    

    The cause (at least for my error) is that input$col is a string and you're treating it as an integer. There are two possible fixes:

    1. Change your selectInput to a numericInput, which means that now input$col returns an integer, or
    2. Manually convert input$col to an integer with col <- as.integer(input$col)

    Using the second approach, here's the complete code.

    runApp(shinyApp(
      ui = fluidPage(
        titlePanel("Data"),
        sidebarLayout(
          sidebarPanel(
            textInput("from","Missing",
                      value="Enter characters"),
            textInput("to","Missing",
                      value="Enter characters"),
            selectInput("col","Select Column",
                        choices = c(1:6),
                        selected=1)),
          mainPanel(
            tableOutput('contents')
          )
        )
      ),
      server = function(input, output) {
        dataset.temp <- file
        output$contents <- renderTable({
            col <- as.integer(input$col)
            dataset.temp[,col] <- gsub(input$from, input$to,dataset.temp[,col])
          dataset.temp
        })
      }
    
    ))
    

    I don't know what file you're using so I just used my own csv file and it works