R Shiny - Using Selectinput as column selection to subset data frame

♀尐吖头ヾ 提交于 2021-01-28 11:10:00

问题


I am using Shiny that takes in a user's txt file. The files composition is completely up to the user - there are no set headers for the file.

data_vals <- reactive({
    file1 <- input$file1
    if (is.null(file1))return(NULL)
    read.table(fill=TRUE,file=input$file1$datapath, header=TRUE, colClasses = 
    "factor")})

From this file, I create a drop down list from the header file that the user submitted:

observe({
  req(input$file1)
  dsnames <- names(data_labels())
  cb_options <- list()
  cb_options[dsnames] <- dsnames
  output$choose_filt1<- renderUI({
   selectInput("filt1", "Filter Level 1", cb_options)
  })
 })

Then, checkboxes of the unique items in the list are shown for the user to de-select.

 observe({
  filt1_data <- data_labels()[,input$filt1]
  filt1_uni <- unique(filt1_data)
  output$inCheckboxGroup1 <- renderUI({
   checkboxGroupInput("inCheckboxGroup1", "Filter Level 1 Options:",
                      choices=filt1_uni,
                      selected=filt1_uni)
  })
 })

I would like to use some type of subsetting to filter data_vals by the column (namely input$filt1) and by the boxes checked (input$inCheckboxGroup1). I am unsure how to do this, as subset(data_vals, NAME %in% input$inCheckboxGroup1) is looking for the NAME as the column header, rather than looking as the input selected by the user.

I have attempted to use:

subset(data_vals, input$inCheckboxGroup1 %in$ input$inCheckboxGroup1)

However, this does not produce a table (it's blank). I have also used: subset(data_vals, Column1Header %in% input$inCheckboxGroup1), which works, so I know it's not the checkbox part of the code.

Is it possible to use subsetting in the way I'm describing, or is there another tool to use?


回答1:


I think you can solve your issue by not using subset, since your column name is a variable. See the example below:

A = 1
B ='am'

# This does not work
mtcars2 = subset(mtcars, B %in% A)

# This works
mtcars2 = mtcars[mtcars[,B] %in% A,]

So in your case you could use:

data_vals = data_vals[data_vals[,input$filt1] %in% input$checkboxGroup1,]

Hope this helps!



来源:https://stackoverflow.com/questions/48532858/r-shiny-using-selectinput-as-column-selection-to-subset-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!