firmo23
firmo23

Reputation: 8404

Subset dataframe by combination of column names in a shiny app

I have the dataframe below:

DF2 = data.frame(agency_postcode = factor(rep(c(12345,45678,24124,32525,32325),2)),
                 car_group=factor(rep(c("Microcar","City car","Supermini","Compact","SUV"),2)),
                 transmission=factor(rep(c("automatic","manual"),5)))

and I have a shiny from which the user select one or more column names. What I want to achieve is after selecting a column name to have return all the values of the dataframe equal to the first row of this column.The same logic should be applied when more than one columns selected.So for example if I select all three columns then the first row of the dataframe must be returned instead of none.

#ui.r
library(shiny)
library(DT)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
                 selectInput("sel","Filter by:",
                             choices = colnames(DF2),
                             multiple=T,selected = "agency_postcode")

    ),
    mainPanel(
      DT::dataTableOutput("D")

    )
  )
)
#server.r
#server.r
library(shiny)
library(DT)
server <- function(input, output) {

  output$D<-renderDataTable({
    DE<-DF2[ which(DF2[,input$sel] %in% DF2[1, input$sel]), ]
    datatable(DE)
  })

}

Upvotes: 1

Views: 610

Answers (1)

akrun
akrun

Reputation: 886938

We just need to specify the rowindex, column name (or column index) and drop to take care off cases to avoid simplifying the dimensions from data.frame to vector for single column, single row cases as by default (drop = TRUE) if we check ?Extract

x[i, j, ... , drop = TRUE]

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.

DE <- DF2[1, input$sel, drop = FALSE]

With the change, the app works fine

enter image description here

Upvotes: 1

Related Questions