使用 table() 函数时闪亮的仪表板 "Error in unique.default(x, nmax = nmax)"

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

我试图在闪亮的仪表板上绘制一个相当简单的图,但是我收到此错误:

 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

我的代码如下所示(与 hello world 示例几乎没有任何不同):

## 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)

错误必须是在我使用 table() 函数时出现的(因为它在原始代码中的行 #38 中),但错误消息太不具体,我无法找出怎么了...

有人建议如何解决这个问题吗?

您的 dat 对象是响应式的,因此请尝试调用 tab <- table(dat())。此外,将响应式调用放在渲染函数中,如下所示:

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

作为一般的编码习惯,我还会避免重用变量名。