首页 > 解决方案 > 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)

标签: rshiny

解决方案


这是一个建议;我已经简化了您的代码以定义一个全局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)

在此处输入图像描述


推荐阅读