0

我是 Shiny 和 R 的新手,所以不要想太多。我可以在传递数据帧之前使用 Shiny 的 UI 部分过滤数据帧plot_ly吗?

plot_ly我正在尝试在 SERVER 部分中的命令之前的数据帧过滤器语句中使用 UI 单选按钮选择(例如 1.75 )中的数值

plot_ly我可以很好地在标题中显示捕获的值,所以我猜它是一个字符/字符串值,但变化as.numeric()似乎也没有帮助。

我试过了 :

df2 <- filter(df,  price == input$radio )
#which fails with:
#Can't access reactive value 'gaspricer' outside of reactive consumer.
reactive{{ df2 <- filter(df, price == as.number(input$radio) })
#which fails  

或两个阶段:

myvar <- some_function_of ( input$radio )    
df2 <- filter(df,  price == myvar )
#which also doesn't fool the interpreter

我想知道如果我将过滤放在plot_ly语句中,我是否可以让动态解释器高兴,比如 plotly( data = filter(df, ... ), variables ) (如果这在 R/plot_ly 中甚至有效)但是如果我这样做了,我无法弄清楚如何引用我需要取消引用 x 和 y 变量的选定列名的新数据框名称,例如df[[input$xcol]] 因为~[[input$xcol]]似乎不起作用。

任何聪明都将不胜感激。我已经超出了我的深度。

讨论:

我可以使用reactive({...})语法或类型语法来从语句df[[input$myvar]]中获取选定的数据框字段。这么多的作品。但在声明之外,我遇到了问题。selectInput()plot_ly()plot_ly

我现在想做的是使用 UI 部分中的三个单选按钮组来选择三个值来过滤数据帧,然后在 SERVER 部分中对其运行 plot_ly。如果它是一个单选按钮组,也许我可以选择要使用的过滤器语句,但我认为,但是对于其中的几个,我们现在可以达到 4x4x4 或更多可能的过滤器语句,这变得越来越尴尬。

4

1 回答 1

2

您的错误的可重现示例/代码:

library(shiny)
library(tidyverse)

ui <- fluidPage(
  numericInput(
    inputId = "radio", 
    label = "Pick a value", 
    value = 6, 
    min = 3.5, 
    max = 8, 
    step = 0.1
  ), 
  
  tableOutput(outputId = "filtered")
  # <-- Yours is a plotOutput, I suppose --> #
)

server <- function(input, output, session) {
  df2 <- dplyr::filter(iris, Sepal.Length == input$radio)
  
  output$filtered <- renderTable(df2())
}

shinyApp(ui, server)

Error : Can't access reactive value 'radio' outside of reactive consumer.
i Do you need to wrap inside reactive() or observer()?

解决方案:

做出df2反应:

server <- function(input, output, session) {
  df2 <- reactive({
    dplyr::filter(iris, Sepal.Length <= input$radio)
  })
  
  output$filtered <- renderTable(df2())
}

解释:

要从输入中读取,您必须处于由类似renderText()or之类的函数创建的反应式上下文中reactive()
〜掌握闪亮,哈德利威克姆。


于 2021-06-21T20:01:05.107 回答