[英]how to delete warnings in reactive inputs in shiny
谁能告诉我为什么在第一个selectInput
小部件中更改数据集时会出错? 当我将数据集从diamonds
更改为mtcars
我得到一个错误:仅在1秒钟mtcars
input$bins
和绘图中Could not find 'carat'
,然后一切正常。 为什么会这样?
library(shiny)
library(ggplot2)
data(diamonds)
data(mtcars)
ui <- fluidPage(
column(3,
selectInput("data", "", choices = c('mtcars', 'diamonds')),
uiOutput('server_cols'),
uiOutput('server_bins')
),
column(9,
plotOutput("plot")
)
)
server <- function(input, output) {
data <- reactive({
switch(input$data,
diamonds = diamonds,
mtcars = mtcars)
})
output$server_cols <- renderUI({
data <- data()
nam <- colnames(data)
selectInput('cols', "Choose numeric columns:", choices = nam[sapply(data, function(x) is.numeric(x))])
})
output$server_bins <- renderUI({
if (!is.null(input$cols)) {
df <- data()
x <- eval(input$cols)
max_value <- max(df[,x])
sliderInput('bins','Choose number of bins:', min = 0.1,
max = max_value,
value = max_value/2)
}
})
output$plot <- renderPlot({
if (!is.null(input$cols) & !is.null(input$bins)) {
basicData <- data()
var <- eval(input$cols)
ggplot(basicData, aes_string(var)) +
geom_histogram(binwidth = input$bins, color = 'white', fill = 'red')
}
})
}
shinyApp(ui, server)
您各自的输出对象会响应您输入变量的任何更改。 因此,当您通过input$data
更改数据集时,尽管input$cols
尚未调整,但图会自行重建。 实际上,尝试将一些print("a")
插入到output$plot
内,以查看如果更改input$data
最多可以调用三次。
解决方法是重新考虑您的反应逻辑,让您的元素仅响应特定的更改,以获得某种响应“线程”。
例如, input$data
应该只触发output$server_cols
。 并且output$server_bins
仅应由input$cols
触发(因为这已经暗示了input$data
之前已更改)。 最终, output$plot
仅需侦听input$bins
更改(因为input$cols
和input$data
更改始终会导致input$bins
更改,因为它位于线程末尾)。
这是我使用isolate
建议。
library(shiny)
library(ggplot2)
data(diamonds)
data(mtcars)
ui <- fluidPage(
column(3,
selectInput("data", "", choices = c('mtcars', 'diamonds')),
uiOutput('server_cols'),
uiOutput('server_bins')
),
column(9,
plotOutput("plot")
)
)
server <- function(input, output) {
data <- reactive({
switch(input$data, diamonds = diamonds, mtcars = mtcars)
})
output$server_cols <- renderUI({
data <- data()
nam <- colnames(data)
selectInput('cols', "Choose numeric columns:", choices = nam[sapply(data, function(x) is.numeric(x))])
})
output$server_bins <- renderUI({
if (!is.null(input$cols)) {
df <- isolate(data())
x <- eval(input$cols)
max_value <- max(df[,x])
sliderInput('bins','Choose number of bins:', min = 0.1, max = max_value, value = max_value/2)
}
})
output$plot <- renderPlot({
if (!is.null(isolate(input$cols)) & !is.null(input$bins)) {
basicData <- isolate(data())
var <- eval(isolate(input$cols))
ggplot(basicData, aes_string(var)) +
geom_histogram(binwidth = input$bins, color = 'white', fill = 'red')
}
})
}
shinyApp(ui, server)
如果要根据其他输入更改输入元素,则可能还需要查看updateSelectInput
和updateSliderInput
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.