r - 为 Shiny 的应用程序创建动态输入字段

标签 r shiny

我使用以下数据框来构建一个 Shiny 的应用程序:

listIDs <- c(100,100,100,100,200,200,200,200),
values <- c(2.12, 2.43, 2.12, 4.45, 3.23, 4.23, 3.23, 4.23),  
horses <- c(2.1, 3.2, 4.1, 4.2, 5.4, 4.7, 2.8, 2.0),  
month <- c("JAN", "FEB", "JAN", "FEB","MAY","APRIL","MAY", "APRIL"),
df <- data.frame(listIDs, values, horses, month),

我正在构建一个带有以下选项卡的 Shiny 应用程序:

ui.R

shinyUI(fluidPage(

#outlinen title
titlePanel(title = "This is the title"),
sidebarLayout(
 sidebarPanel(
  
  selectInput("var1", "Select the eventID", choices = listIDs),
  selectInput("var2", "Select the eventID", choices = month),
  br()
 ),

 mainPanel(("Personal information"),
          plotOutput("myhist"))
)
)) 

服务器.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output){

output$myhist <- renderPlot({

df_graph <- df[df$listIDs == input$var1,]
df_graph <- df_graph[df_graph$month == input$var2,]

ggplot(data=df_graph, aes(x=month, y=values, group = horses)) +
  geom_line() + geom_point() + theme(axis.text.x = element_text(angle = 90, hjust = 1))

})
})

一切正常,但问题是,当我在第一个选择框中选择 100 时,我仍然得到选项“JAN”、“FEB”、“MRT”、“APRIL”(而我只应该得到 JAN 和 FEB) 。关于如何使这种动态化有什么想法吗?

最佳答案

与月份选择相对应的 selectInput 元素应根据 input$var1 的值动态呈现。这是一个简单的例子:

shinyApp(
    ui = fluidPage(

        titlePanel(title = "This is the title"),
        sidebarLayout(
            sidebarPanel(
                selectInput("var1", "Select the eventID", 
                            choices = listIDs
                ),
                uiOutput("select_month_ui"),
                br()
            ),
            mainPanel(
                "Personal information",
                plotOutput("myhist")
            )
        )
    ),
    server = function(input, output) {
        output$select_month_ui <- renderUI({
            selectInput("var2", "Select the eventID", 
                        choices = df[df$listIDs %in% input$var1,"month"]
            )
        })

        output$myhist <- renderPlot({
            df_graph <- df[df$listIDs == input$var1,]
            df_graph <- df_graph[df_graph$month == input$var2,]

            ggplot(data = df_graph, 
                    aes(x = month, y = values, group = horses)) +
                geom_line() + geom_point() + 
                theme(axis.text.x = element_text(angle = 90, hjust = 1))
        })
    }
)

selectInput 对象已从 UI 代码移动到服务器代码中,如下所示

    output$select_month_ui <- renderUI({
        selectInput("var2", "Select the eventID", 
                    choices = df[df$listIDs %in% input$var1,"month"]
        )
    }) 

并替换为 uiOutput("select_month_ui")

关于r - 为 Shiny 的应用程序创建动态输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212071/

相关文章:

r - 在 R 中向量化循环

r - 如何在申请家庭内分配?

通过成对比较和多个标准从数据框中删除观察结果

r - 从 Shiny 的输入创建数据框

r - 基于正则表达式以 Shiny 的方式突出显示 DT 中的单词

arrays - 将矩阵合并到R中的数组

r - 使用 ggplot2 创建一个带有条形项目符号的条形图

r - 在 Shiny 应用页面的标题栏中显示图标

根据服务器中的条件逻辑呈现 Shiny 的用户输入

r - 在 Shiny 中,从 react 对象的列中选择唯一值以用作输入选择