R:使用 if 条件闪亮的 renderUI 过滤来自 selectInput 的结果

R: filter result from selectInput by renderUI shiny with if condition

在下面的示例中,我有四个 selectInput,但在我真正闪亮的应用程序中我实际上有六个。我希望第一棵树 selectInput(major,gender,course) 中的选择更改最后一棵树中的可能选择(学生姓名)。所以前三个 selectInput 就像最后一个的过滤器一样工作。

我在下面有一些代码,但效果不佳。如果有人能帮忙,非常感谢!

这是数据示例
df = data.frame(Studentname = c("aa","aa","aa","bb","bb","bb","cc","cc","dd","ee","ff","gg"),
                Major = c("A","A","B","B","B","B","C","C","A","A","C","C"),
                Gender = c("female","female","female","male","male","male","male","male","female","female","male","male"), Course = c("01","02","03","01","03","04","02","04","01","03","02","04"),stringsAsFactors=F)
代码:
 library(shiny)

ui = (fluidPage(
  titlePanel("Test"),
  sidebarLayout(
    sidebarPanel(
      uiOutput("choose_maj"),
      uiOutput("choose_gen"),
      uiOutput("choose_cou"),
      uiOutput("choose_stu")
    ),
    mainPanel()
  )
  
))

server = function(input,output,session){
  output$choose_maj = renderUI({
    selectInput("maj.in","Choose Major",
                choices = c("All",unique(df$Major)),selected="All")
  })
  
  output$choose_gen = renderUI({
    selectInput("gen.in","Choose Gender", 
                choices= c("Both",unique(df$Gender)),selected = "Both")
  })
  
  output$choose_cou = renderUI({
    selectInput("cou.in","Choose Course", 
                choices= c("All",unique(df$Course)),selected = "All")
  })
  
  output$choose_stu = renderUI({
    
    if(input$maj.in != "All"){
      dat <- df[which(df$Major == input$maj.in),]
  
    }
    if(input$gen.in != "Both"){
      dat <- df[which(df$Gender == input$gen.in),]

    }
    if(input$cou.in != "All"){
      dat <- df[which(df$Course == input$cou.in),]
    }
    
    selectInput("stu.in", "Choose Student Name", 
                choices  = as.list(unique(dat$Studentname)),
                selected = "All")
  })
}

runApp(list(ui = ui, server = server))

如果您只是将 data.frame 的副本提供给 renderUI 函数,您就可以执行所有不同的子集。

这对我有用:

output$choose_stu = renderUI({

    dat <- df

    if(input$maj.in != "All"){
        dat <- dat[which(dat$Major == input$maj.in),]

    }
    if(input$gen.in != "Both"){
        dat <- dat[which(dat$Gender == input$gen.in),]

    }
    if(input$cou.in != "All"){
        dat <- dat[which(dat$Course == input$cou.in),]
    }

    selectInput("stu.in", "Choose Student Name", 
                choices  = as.list(unique(dat$Studentname)),
                selected = "All")
})