[英]R, Shiny: subset a dataframe based on condition with reactive column name
使用 R/Shiny,我想绘制用户选择的变量,但值低于某个阈值。
我知道可以使用 ggplot 进行过滤,但由于各种原因,我希望 dataframe 被反应性子集化。 在下面的示例中,我希望根据用户选择的列对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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.