【发布时间】:2019-09-16 17:56:42
【问题描述】:
我尝试在我的数据分析中添加过滤器。过滤器 (inputF2) 是用户选择的类别 (xInput) 中的一个项目。
然后我想过滤掉数据以进行汇总分析并绘制平均值。但是,一旦我编写了 if 语句,程序就无法运行。
library(datasets)
library(shiny)
library(dplyr)
library(ggplot2)
library(DT)
library(crosstalk)
data("iris")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Analyze Iris table"),
# Sidebar with a dropdown menu selection input for key measurecomponent
sidebarLayout(
sidebarPanel(
selectInput("yInput", "Measuring element: ",
colnames(iris), selected = colnames(iris)[2]),
selectInput('xInput', 'Grouper: ',
colnames(iris), selected = colnames(iris)[5])
),
# Show a plot of the generated distribution
mainPanel(
uiOutput('filter'),
plotOutput("barPlot"),
DTOutput('table1')
)))
server <- function(input, output) {
output$filter = renderUI({
selectInput('inputF2', 'Filter Item: ',
c('Null', unique(iris %>% select(input$xInput))))
})
if(input$inputF2 != 'Null') {
iris_sub = reactive({
iris %>% filter_at(input$xInput == input$inputF2)
})
} else{ iris_sub = iris}
by_xInput <- reactive({
iris_sub %>%
group_by_at(input$xInput) %>%
summarize(n = n(), mean_y = mean(!! rlang::sym(input$yInput)))
})
output$barPlot <- renderPlot({
# as the input is a string, use `aes_string`
ggplot(data = by_xInput(), aes_string(x = input$xInput, y = "mean_y")) +
geom_bar(stat = 'identity')
})
output$table1 = renderDT(
datatable(by_xInput())
)
}
shinyApp(ui = ui, server = server)
这是我收到的错误消息:
.getReactiveEnvironment()$currentContext() 中的错误: 如果没有活动的反应上下文,则不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)
【问题讨论】:
-
我想你可能需要
%>% filter_at(vars(input$xInput), any_vars(. == input$inputF2)) -
另外,我发现你在
if条件中使用=而不是== -
谢谢@akrun!但是我仍然在反应式环境中遇到同样的错误......
-
@akrun,是的...... if 语句中的 == 错误是一个错字。而且我不知道为什么代码被分成所有这些部分:(((如果难以阅读,抱歉。