ChMoe ChMoe - 2 months ago 9
R Question

R Shiny: Print Table with selected columns

I am trying to print a table upon checkbox selection. This works fine but I don´t want to print all columns, i.e. only "name" and "color".
Unfortunately, I can´t find a command to show specific columns. I thought that

input$color
can solve the problem, but I was not able to run the script properly.
Here is my minimum example:

mydat <- data.table( id=c(1,2,3,4),
londd=c(20, 38, 96, 32),
latdd=c(60, 56, 30, 31),
material=c("stone", "water,sand", "sand", "wood"),
application=c("a","b","c","d"),
name=c("1","2","3","4"),
color=c("red","green","blue","yellow"))

#Set up ui
ui <- shinyUI(fluidPage(
sidebarPanel(h5("", width=2),
checkboxGroupInput(inputId="MatFlag",label=h4("Material"),
choices=setNames(object=c("stone","water","sand", "wood"),
nm=c("stone", "water", "sand", "wood"))
),
checkboxGroupInput(inputId="AppFlag",label=h4("Application"),
choices=setNames(object=c("a","b","c","d"),
nm=c("a","b","c","d"))
),
position="left"),

#App mainPanel content and styles
mainPanel("Plot_and_table","Plot and Table",
"button_plot_and_table",size="large",dataTableOutput("TestTable"))))

#Set up server
server <- function(input, output){

#Filter data
datFilt <- reactive({
MatSearch <- paste0(c('xxx',input$MatFlag),collapse = "|")
MatSearch <- gsub(",","|",MatSearch)
mydat[grepl(MatSearch,material) & application %in% input$AppFlag]
})

output$TestTable <- renderDataTable({datFilt()
}, options = list(pageLength=5))


}

#Run app
shinyApp(ui = ui, server = server)

Answer

If just the subsetting all you want, this should be fine:

 datFilt <- reactive({
    MatSearch <- paste0(c('xxx',input$MatFlag),collapse = "|")
    MatSearch <- gsub(",","|",MatSearch)
    testdata <- mydat[grepl(MatSearch,material) & application %in% input$AppFlag]
    testdata[,c("name","color"), with=FALSE]
  })
Comments