r - R,Shiny:根据具有反应列名称的条件对数据框进行子集化
问题描述
使用 R/Shiny,我想绘制用户选择的变量,但值低于某个阈值。
我知道可以使用 ggplot 进行过滤,但由于各种原因,我希望数据帧被反应性地子集化。在下面的示例中,我想rv$m
根据用户选择的列进行子集化。基于this answer,我尝试根据colnames进行过滤,但无济于事。我还尝试了这里和那里收集的各种其他解决方案(不太了解它们),见下文。
# Test of shiny app for a histogram
library(shiny)
library(ggplot2)
library(dplyr)
dataForPlot <- iris
# Define UI for app that draws a histogram ----
ui <- fluidPage(
selectInput(inputId = "dimToPlot", label="Dim to plot:",choices = c("Length","Width")),
plotOutput(outputId = "distPlot")
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
rv <- reactiveValues()
observeEvent(input$dimToPlot,{
rv$colName <- paste0("Petal.",input$dimToPlot) # variable that will be displayed
rv$mfull <- dataForPlot[rv$colName] # dataframe subsetted to the proper var, ALL OBS
# All the ways that I could not make work
rv$m <- rv$mfull[rv$mfull[colnames(rv$mfull)==rv$colName] <2, ]
rv$m <- subset(rv$mfull, !!get(rv$colName) <2, select = c(rv$colName))
rv$m <- rv$mfull %>% dplyr::filter(!!rv$colName <2)
})
# Histogram ----
output$distPlot <- renderPlot({
ggplot(environment = environment(),
data=rv$m, aes(x=.data[[rv$colName]])) +
geom_histogram(color="white", fill="#2b6a6c",bins = 10,boundary=0 )
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
解决方案
这是一个建议;我已经简化了您的代码以定义一个全局data()
反应式表达式,这是您想要的子集。每次用户通过eventReactive
.
# Test of shiny app for a histogram
library(shiny)
library(ggplot2)
library(dplyr)
dataForPlot <- iris
# Define UI for app that draws a histogram ----
ui <- fluidPage(
selectInput(inputId = "dimToPlot", label="Dim to plot:",choices = c("Length","Width")),
plotOutput(outputId = "distPlot")
)
# Define server logic required to draw a histogram ----
server <- function(input, output) {
column <- reactive({paste0("Petal.",input$dimToPlot)})
data <- eventReactive(input$dimToPlot, {
dataForPlot %>%
select(column()) %>%
filter(get(column()) < 2)
})
# Histogram ----
output$distPlot <- renderPlot({
ggplot(environment = environment(),
data = data(),
aes_string(x = column())) +
geom_histogram(color="white", fill="#2b6a6c",bins = 10,boundary=0)
})
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
推荐阅读
- java - 无法解析符号 textView - Android Studio
- sql - 如何从sqlite中的表中选择值X在另一个值C的某个半径R内的所有元素?
- c# - Aforge 程序仅在调试模式下工作
- android - Firestore 数据库结构
- android - 将折线添加到具有不同颜色android的谷歌地图
- firebase - Firebase 数据库计费使用情况
- android - 如何检查用户是否在 Android、Google Play 中拥有有效订阅?
- c++ - 带有基于模板的 API 的 C++ Memory-Mapped-IO
- scala - 如何避免在具有家族多态性的 Scala 中调用 asInstanceOf
- javascript - javascript - 在另一个元素下放置一个矩形