簡體   English   中英

R Shiny-根據用戶選擇的輸入將新列添加到數據框

[英]R Shiny - Add new column to dataframe based on user selected input

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 <- 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 <- 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())})  
}

我目前正在努力根據用戶的選擇在數據框中生成新列。 到目前為止,它根據下拉列表和復選框顯示了我想要的內容,但是我無法對此進行任何進一步的調整。 我不確定我的問題所在-我的表格渲染不正確,我是否未正確添加新列?

我嘗試訪問input $ metalab和input $ metaval,但它們在renderUI / renderText上下文之外返回NULL。 我嘗試根據用戶選擇簡單地復制一列,但這也不起作用:

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

任何幫助是極大的贊賞! 抱歉,很長時間了!

嗨,這是您想要做的事情嗎?

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)})  

}

我所做的是,我已將所有輸出分配從反應型陳述中刪除。 這主要是我使代碼更穩定。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM