R:使用if条件,使用renderUI glig的selectInput过滤结果

时间:2015-10-20 16:08:24

标签: r if-statement shiny render

在下面的例子中,我有四个selectInput,但在我真正闪亮的应用程序中,我实际上有六个。我想在第一个树selectInput(主要,性别,课程)中选择更改最后一个(studentname)中的可能选择。所以前三个selectInput就像最后一个的过滤器一样。
  • 例如,如果用户在性别selectInput中选择“男性”,那么 studentname selectInput中的选项应仅显示名称 男学生
  • 如果用户在性别selectInput中选择“male”,在major中选择“A” selectInput,然后studentname selectInput中的选项应该 仅显示主要A的男学生姓名。

我下面有一些代码,但效果不好。如果有人能提供帮助,非常感谢!

这是数据示例
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))

1 个答案:

答案 0 :(得分:2)

如果您只是将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")
})