【问题标题】:R Shiny: How to use a UI textinput from ui, in the server section for subsetting a data frame?R Shiny:如何在服务器部分使用来自 ui 的 UI 文本输入来对数据框进行子集化?
【发布时间】:2020-06-18 10:54:55
【问题描述】:

我没有在其他地方看到这个问题得到明确的回答。我想要一个“textInput”框,用户可以在其中输入国家名称“Argentina”。根据该输入,在代码的服务器部分,我想按该国家/地区名称对预加载的数据框进行子集化。

有人可以帮助我如何做到这一点吗?非常感谢。

以下是使用 mtcars 作为示例数据的代码。

# Some Sample data to run app using mtcars
mtcars$Primary<- rownames(mtcars)
mtcars$Area <- "Argentina"
mtcars$Y2016<- mtcars$mpg
mtcars$Element <- "Gross Production Value (constant 2004-2006 million US$)"


# Defining UI ----
ui <- pageWithSidebar(

          # App title ----
          headerPanel("Subsector Selection Tool"),

          # Sidebar panel for inputs ----
          sidebarPanel(

            # Input: Country name
            textInput("country", "Please enter country name", "")#,

          ),

          # Main panel for displaying outputs ----
          mainPanel("")
)



# Use user input (country name) to subset desired dataframe. 
server <- function(input, output) {

#Trying to make user inputed country name into an object to be used in "reactive" code below, which in turn is be used to make dataset for graphing
country_interest <- reactive({
paste(input$country)
})


#Here I am trying to make the data analysis code run and create desired dataset for graphing, and 
subsetting for country selected by user
Value_c_e_PRIM_x  <- reactiveValue({

Value_c <- Value[which(Value$Area==country_interest),]

})

【问题讨论】:

    标签: shiny subset reactive


    【解决方案1】:

    这是一个满足您需求的应用程序的最小示例:

    library(shiny)
    library(dplyr)
    
    mtcars$country <- rep(c("Argentina", "Chile"), 16)
    
    ui <- fluidPage(
    
      textInput("country", "Please enter country name", ""),
      tableOutput("table")
    
    )
    
    server <- function(input, output, session) {
    
       data <- reactive(mtcars %>% filter(country == input$country))
    
       output$table <- renderTable({
       data()
       })
    }
    shinyApp(ui, server)
    

    但是,请注意:

    • 在您的情况下,最好将过滤选项放在 selectInput() 中,因为您可以在其中放置数据框中已经存在的值。
    • 我发现最好将响应式数据帧放在 reactive 函数中(如我的示例中):在内部对输入进行所有必要的修改,然后在渲染函数中调用该对象(注意括号结束,因为现在是一个反应性的闪亮对象)。

    【讨论】:

    • 非常感谢!这个答案非常有帮助,并帮助我上路。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多