简体   繁体   English

R Shiny-根据用户选择的输入将新列添加到数据框

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

Very new to R Shiny! R Shiny的新手! I've looked through a good 20 questions but they don't necessarily address the problem I'm facing. 我已经仔细研究了20个问题,但不一定能解决我所面临的问题。

I have a few dataframes generated from API calls that look something like this: 我有一些通过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           

My goal is to allow users to select a column from the dataframe using a dropdown, select some values to compare from that column using some checkboxes, and add a new column to the same frame reflecting the comparisons that they wanted to make. 我的目标是允许用户使用下拉列表从数据框中选择一列,使用某些复选框从该列中选择一些值进行比较,然后将新列添加到同一框中以反映他们想要进行的比较。 It should look like this: 它看起来应该像这样:

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

I'm currently struggling to produce a new column in the dataframe based off the user's selections. 我目前正在努力根据用户的选择在数据框中生成新列。 So far, it displays what I would like it to in terms of the dropdown and checkboxes but I wasn't able to move any further with that. 到目前为止,它根据下拉列表和复选框显示了我想要的内容,但是我无法对此进行任何进一步的调整。 I'm not exactly sure where my problem lies - is my table rendering improperly, am I not adding a new column correctly? 我不确定我的问题所在-我的表格渲染不正确,我是否未正确添加新列?

I tried to access input$metalab and input$metaval but they return NULL outside a renderUI/renderText context. 我尝试访问input $ metalab和input $ metaval,但它们在renderUI / renderText上下文之外返回NULL。 I've tried simply duplicating a column based on user choice but this doesn't work either: 我尝试根据用户选择简单地复制一列,但这也不起作用:

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

Any help is greatly appreciated! 任何帮助是极大的赞赏! Sorry for the long blurb! 抱歉,很长时间了!

Hi is this something in the way of what you want to do? 嗨,这是您想要做的事情吗?

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

}

What I have done is that I have pulled all asignments of outputs out of the reactive statment. 我所做的是,我已将所有输出分配从反应型陈述中删除。 This is mainly I to make the code more stable. 这主要是我使代码更稳定。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM