R Shiny - 根据用户选择的输入

时间:2018-01-03 20:33:45

标签: r shiny

R Shiny非常新!我已经看了很多20个问题,但它们并不一定能解决我面临的问题。

我有一些API调用生成的数据帧,如下所示:

Project.ID        Author.ID    Author.Name     Fav.Color
Test_Project1      1234             Bob        Green
Test_Project1      2345            Jane         Blue
Test_Project1      2687            Eric         Blue
Test_Project1      8765            Tom           Red           

我的目标是允许用户使用下拉列表从数据框中选择一列,使用一些复选框从该列中选择一些值进行比较,然后将新列添加到相同的框架,以反映比较他们想要做的。它应该是这样的:

Project.ID      Author.ID    Author.Name     Fav.Color    RedvBlue   GreenvRed
Test_Project1    1234            Bob        Green          NA      Green
Test_Project1    2345            Jane         Blue        Blue     NA   
Test_Project1    2687            Eric         Blue        Blue     NA
Test_Project1    8765            Tom           Red         Red     Red

ui.R

ui <- fluidPage(

  sidebarPanel(
     selectInput("viewType", 
                 label = "Select to view:",
                 choices = c(' ', "Projects"), #will have other dataframes to select from 
                 selected = ' '),
     conditionalPanel(
       condition = "input.viewType =='Projects'",
       uiOutput("projectSelection"),
       uiOutput("showMeta"), 
       uiOutput("showVal"),
       textOutput("text")
     )
  ),

  mainPanel(
    DT::dataTableOutput("mytable")
  )
)

server.R

server <- function(input, output) {

    viewSelection <- reactive({
      if(input$viewType == "Projects"){
        projectDT <- getJSON("an API url")

        #replace spaces with dots in headers
        names(projectDT) <- gsub(" ", ".", names(projectDT))

        #show table
        output$mytable <- DT::renderDataTable(DT::datatable(projectDT))


        #Display columns from project to view
        output$showMeta <- renderUI({
          selectInput("metalab",
                      "Metadata Label:",
                      c(" ", unique(as.vector(colnames(projectDT))))
          )
        })

        #Display unique column values to choose from in checkbox
        #Gives Warning: Error in [.data.frame: undefined columns selected
        output$showVal <- renderUI({
          checkboxGroupInput("metaval",
                             "Metadata Value:",
                             choices = unique(as.vector(unlist(projectDT[input$metalab])))
          )
        })

      }

    })

    output$mytable <- DT::renderDataTable({DT::datatable(viewSelection())})  
}

我目前正在努力根据用户的选择在数据框中生成新列。到目前为止,它在下拉列表和复选框方面显示了我想要的内容,但我无法继续使用它。我不确定我的问题在哪里 - 我的表格渲染不正确,我没有正确添加新列吗?

我尝试访问输入$ metalab并输入$ metaval,但它们在renderUI / renderText上下文之外返回NULL。我试过根据用户选择简单地复制一列,但这也不起作用:

projectDT['newCol'] = projectDT[input$metalab]

非常感谢任何帮助!对不起,长篇大论!

1 个答案:

答案 0 :(得分:0)

嗨这是你想要做的事情吗?

server <- function(input, output, session) {
  # update datatable
  viewSelection <- reactive({
    if(input$viewType == "Projects"){
      projectDT <- read.table(header = TRUE,
                              text = "Project.ID,Author.ID,Author.Name,Fav.Color
Test_Project1,1234,Bob,Green
Test_Project1,2345,Jane,Blue
Test_Project1,2687,Eric,Blue
                              Test_Project1,8765,Tom,Red",
                              sep = ",")

      #replace spaces with dots in headers
      names(projectDT) <- gsub(" ", ".", names(projectDT))

      projectDT



    }

  })
  #show table
  output$mytable <- DT::renderDataTable(DT::datatable(viewSelection()))
  #Display columns from project to view
  observeEvent({input$addCol},{
    insertUI(
      selector = "#addCol",
      where = "beforeBegin",
      ui = div(
        uiOutput(paste0("showMeta",input$addCol)),
        uiOutput(paste0("showVal",input$addCol))
      )
    )
  })
  lapply(1:5, function(idx){
    output[[paste0("showMeta",idx)]] <- renderUI({
      selectInput(inputId =  paste0("metalab",idx),
                  label =  "Metadata Label:",
                  choices =  c(" ", unique(as.vector(colnames(viewSelection())))),
                  selected = input[[paste0("metalab",idx)]]
      )
    })
  })
  lapply(1:5,
         function(idx){
           output[[paste0("showVal",idx)]] <- renderUI({
             req(input$addCol >= idx)
             checkboxGroupInput(paste0("metaval",idx),
                                "Metadata Value:",
                                choices = unique(as.vector(unlist(viewSelection()[[input[[paste0("metalab",idx)]]]]))),
                                selected = input[[paste0("metaval",idx)]]
             )
             })
         })

  output$showMeta <- renderUI({
  })
    #Display unique column values to choose from in checkbox
    #Gives Warning: Error in [.data.frame: undefined columns selected
  output$showVal <- renderUI({
    checkboxGroupInput("showVal",
                       "Metadata Value:",
                       choices = unique(as.vector(unlist(viewSelection()[[input$metalab]])))
    )
  })

  output$mytable <- DT::renderDataTable({
    req(input$viewType == "Projects")
    projectDT <- viewSelection()
    dta <- NULL
    if(input$addCol > 0){
      dta <- lapply(seq(input$addCol), function(idx){
        if(!is.null(input[[paste0("metalab", idx)]]) &&
           input[[paste0("metalab",idx)]] != " "){
          ifelse(projectDT[[input[[paste0("metalab", idx)]]]] %in% input[[paste0("metaval", idx)]] ,as.character(projectDT[[input[[paste0("metalab", idx)]]]]),NA)
        }
      })
      names(dta) <- sapply(seq(input$addCol),function(idx){
        paste0("Compare",idx,"_",paste0(input[[paste0("metaval",idx)]],collapse = "vs"))
      })
      dta <- as_data_frame( dta[!sapply(dta,is.null)])
    }
    if(!is.null(dta) &&
       !is.null(projectDT) &&
       nrow(dta) == nrow(projectDT)){
      projectDT <- cbind(projectDT,dta)
    }
    DT::datatable(projectDT)})  

}

我所做的是,我已经从反应性声明中提取了所有输出的输出。这主要是为了使代码更稳定。

希望这有帮助!