Nick Knauer
Nick Knauer

Reputation: 4243

File Input Error in Shiny App

I am making a Shiny App which requires a dataset input. I am able to get it to work with one value in the dataset but when I upload multiple values an error message comes up saying:

Example dataset (csv) that works when inputting:

category
action

Example dataset (csv) that does not work when inputting:

category
action
noir 

Error: replacement has 1 row, data has 0

Below is my ui and server. Completely reproducible set.

It works when I just input the category: "action" but when I input the categories: "action" and "noir" in one csv column, the error comes up.

server:

library(shiny)
library(readr)
library(dplyr)

actor <- c('Matt Damon','George Clooney','Brad Pitt', 'Clive Owen', 'Morgan Freeman', 'Edward Norton', 'Adrian Granier')
category<-c('action', 'action', 'noir', 'action', 'thriller', 'noir', 'action')
movie <- c('Oceans Eleven', 'Oceans Twelve', 'Fight Club', 'Children of Men', 'The Shawshank Redemption', 'American History X', 'Entourage')
movies <- c(21, 23, 26, 12, 90, 14, 1)
cost <- c(210000, 2300000, 260000, 120000, 90000, 140000, 10000)
Type <- c('A','B','C', 'A', 'B', 'C', 'A')

moviedata<-data.frame(actor, category, movie, movies, cost, Type)

shinyServer(function(input,output){
  data <- reactive({
    file1 <- input$file
    if(is.null(file1)){return()} 
    read_csv(file=file1$datapath)

  })
  output$sum <- renderTable({
    if(is.null(data())){return ()}
    test<-subset(moviedata, category %in% data())
    test1<-filter(test, `Type`==input$file4)
    test1$`BUDGET`<-input$file5
    test1$CHECKING<-ifelse(test1$`BUDGET`>test1$cost,"YES", "NO")
    filter(test1, CHECKING=="YES")
  })

  output$tb <- renderUI({
    if(is.null(data()))
      h5("Powered by", tags$img(src='optimatic.png'))
    else
      tabsetPanel(tabPanel("Summary", tableOutput("sum")))
  })

} 
)

ui

library(shiny)
shinyUI(fluidPage(
  titlePanel("Actor Finder"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file","Upload Category List: Must have category as header"),
      selectInput("file4", "Select Type", c("A" = "A",
                                            "B" = "B",
                                            "C" = "C"), selected = "A"),
      numericInput("file5", "Choose cost", 1000000000),
      tags$hr()),    
    mainPanel(
      uiOutput("tb")
    )

  )
 ))

Upvotes: 0

Views: 582

Answers (1)

HubertL
HubertL

Reputation: 19544

Because you read your csv file with readr, it is a tbl_df data.frame, which - unlike base data.frame - dosen't get simplified to a vector when it contains a single column.

Compare:

> c(1,2) %in% tibble(a=c(1,2))[,1]
[1] FALSE FALSE
> c(1,2) %in% tibble(a=c(1,2))[[1]]
[1] TRUE TRUE
> c(1,2) %in% data.frame(a=c(1,2))[,1]
[1] TRUE TRUE
> c(1,2) %in% data.frame(a=c(1,2))[[1]]
[1] TRUE TRUE

You can to use this syntax to take only the first column:

category %in% data()[[1]]

Upvotes: 1

Related Questions