Error: First argument must be a data frame or shared data

Error: First argument must be a data frame or shared data

我想在 shinydashboard 中创建基于 selectorInput 的动态图,但是当我想创建图时出现错误:

First argument, data, must be a data frame or shared data.

当我尝试对数据进行子集化并将它们用作绘图输入时,我的部分代码是服务器部分:

data_sub = reactive({
data_sub_temp = df[df$market == input$market_selector,]
return(data_sub_temp)
  })


  output$market_plot <- renderPlotly({
  plot_ly(
  data = data_sub,
  x = ~ created,
  y = ~ pax,
  group_by = ~ type,
  color = ~ type,
  type = "scatter",
  mode = "lines+markers",
  hoverinfo = 'text',
  text = ~ paste('Year:', created,
                 '</br> </br> Clients: ', pax)
  )  
  })

数据集在UI&Server 代码部分之前加载和预处理。当我在 UI&Server 部分之前使用子集化的数据集时,此代码有效,但在添加 data_sub 部分后我无法使其正常工作。有什么建议吗?谢谢

我认为问题是 dataframe 部分是 reactive,而不是情节。您可以尝试使用 eventHandler 代替。在这种情况下,您需要在 ui 中添加一个 actionButton(可能在 sidebarPanel 中)并在服务器中添加 eventHandler,而不添加 reactive部分。 代码如下。

ui

 actionButton(
      inputId = "submit_loc",
      label = "Submit")

服务器

observeEvent(
    eventExpr = input[["submit_loc"]],
    handlerExpr = {

data_sub <- df[df$market == input$market_selector,]

output$market_plot <- renderPlotly({
  plot_ly(
  data = data_sub,
  x = ~ created,
  y = ~ pax,
  group_by = ~ type,
  color = ~ type,
  type = "scatter",
  mode = "lines+markers",
  hoverinfo = 'text',
  text = ~ paste('Year:', created,
                 '</br> </br> Clients: ', pax)
  )  
  })

})

试试让我知道这是否有效。

Reactive 用于限制在反应过程中重新运行 的内容。 reactive({}) 表达式产生类似于 input$... 表达式的反应。

即在您的示例中,将 data_subrenderPlotly() 表达式中拉出会阻止 renderPlotly 在 df$marketinput$market_selector 更改时从 运行ning 除非您告诉闪亮的 data_sub 必须像你上面所做的那样反应。将 data_subrenderPlotly() 表达式隔离没有什么意义,除非其他 input$... 表达式导致 renderPlotly() 重绘。请参阅 Reactive Tutorial 以获得更好的理解。

如果你希望保持 data_sub 反应性,你需要在你的情节中使用括号符号来调用它。即 data = data_sub()

在您错误地使用 = 运算符时,掌握 R 中的赋值运算符可能也很有用。您的代码仍将 运行,但最好对 data_sub 使用 <- 运算符。参见 Difference between assignment operators in R

最终代码应如下所示:

服务器

data_sub <- reactive({df[df$market == input$market_selector,]})

output$market_plot <- renderPlotly({
  plot_ly(
  data = data_sub(),
  x = ~ created,
  y = ~ pax,
  group_by = ~ type,
  color = ~ type,
  type = "scatter",
  mode = "lines+markers",
  hoverinfo = 'text',
  text = ~ paste('Year:', created,
                 '</br> </br> Clients: ', pax)
  )  
})

尝试使用 data = data_sub() 而不是 data = data_sub

output$market_plot <- renderPlotly({
  plot_ly(
  data = data_sub(),
  x = ~ created,
  y = ~ pax,
  group_by = ~ type,
  color = ~ type,
  type = "scatter",
  mode = "lines+markers",
  hoverinfo = 'text',
  text = ~ paste('Year:', created,
                 '</br> </br> Clients: ', pax)
  )  
  })