Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

r - Shiny Dashboard "Error in unique.default(x, nmax = nmax)" when using table() function

I'm trying to draw a fairly simple plot on a shiny dashboard, however I get this error:

 Warnung: Error in unique.default: unique() kann nur auf Vektoren angewendet werden
  51: unique.default
  49: factor
  48: table
  47: server [C:/.../Dashboard.R#38]
Error in unique.default(x, nmax = nmax) : 
  unique() kann nur auf Vektoren angewendet werden

My code looks like this (barely any different from the hello world example):

## app.R ##
library(shiny)
library(shinydashboard)

# my libraries #
library(dplyr)

ui <- dashboardPage(
  dashboardHeader(title = "My Dashboard"),
  
  dashboardSidebar(),
  
  dashboardBody(fluidRow(
    box(plotOutput("plot1", height = 400)),
    
    box(title = "Controls",
        sliderInput("slider", "Years:", 1970, 2017, 2000))
  ))
)

server <- function(input, output) {
  dat <- read.csv("filename.csv", sep = ",", header = TRUE, encoding = "UTF-8", fill = TRUE)
  
  dat <-
    reactive({
      dat %>%
        filter(year > input$slider) %>%
        select(year)
    })
  
  tab <- table(dat)
  
  output$plot1 <- renderPlot({
    plot(
      tab,
      main = "My Main Title",
      ylab = "Amount",
      xlab = "Year",
      type = "o"
    )
  })
}

shinyApp(ui, server)

The error has to be in my use of the table() function (since that is in line #38 in the original code), but the error message is too unspecific for me to find out what's wrong ...

Does anyone have a suggestion how to fix this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your dat object is a reactive, so try calling tab <- table(dat()) instead. Also, place the reactive call within a render function, like so:

  output$plot1 <- renderPlot({
    tab <- table(dat())
    plot(
      tab,
      main = "My Main Title",
      ylab = "Amount",
      xlab = "Year",
      type = "o"
    )
  })

I'd also avoid reusing variable names as a general coding practice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...