As said in comments, I set up as reactive the ColC choices in server
. To do that, you need to create an input ColC
in the ui
part. I then removed the second column of your dataframe (ColB
) in server
.
I think the solution to your problem is :
as <- data.frame(ColA = c("India","USA","Canada","India","USA","Canada","Australia"),ColB=c("A","B","C","D","E","F","G"),ColC=c("Jan","Jan","Mar","Feb","Jan","Apr","Apr"))
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(selectInput("x","Operations",choices =
c("table"),
multiple=FALSE,selectize = TRUE),
(selectInput("ColC","Choices from ColC", choices = as$ColC,
multiple=TRUE,selectize = TRUE))),
mainPanel(h6("Here it is"),
dataTableOutput("message")
)
)
)
server <- function(input, output, session) {
r1 <- reactive({
if(input$x == "table")
{
tab <- as.data.frame(as[as$ColC %in% input$ColC, ])
tab <- tab[, -2]
}
})
output$message <- renderDataTable({
r1()
})
}
shinyApp(ui, server)
EDIT : you need to transform a table in a dataframe. In order to do that, you need to use as.data.frame.matrix
function as described here (How to convert a table to a data frame). The final code is :
as <- data.frame(ColA = c("India","USA","Canada","India","USA","Canada","Australia"),ColB=c("A","B","C","D","E","F","G"),ColC=c("Jan","Jan","Mar","Feb","Jan","Apr","Apr"))
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(selectInput("x","Operations",choices =
c("table"),
multiple=FALSE,selectize = TRUE),
(selectInput("ColC","Choices from ColC", choices = as$ColC,
multiple=TRUE,selectize = TRUE))),
mainPanel(h6("Here it is"),
dataTableOutput("message")
)
)
)
server <- function(input, output, session) {
r1 <- reactive({
if(input$x == "table")
{
tab <- as.data.frame.matrix(table(as$ColC, as$ColA))
tab <- tab[as$ColC %in% input$ColC, ]
}
})
output$message <- renderDataTable({
r1()
})
}
shinyApp(ui, server)
EDIT #2 : I replace as$ColC
by rownames(tab)
. Also I add library(DT)
in order to put the option rownames = TRUE
in renderDataTable
. Here's the final solution (I hope so) :
as <- data.frame(ColA = c("India","USA","Canada","India","USA","Canada","Australia"),ColB=c("A","B","C","D","E","F","G"),ColC=c("Jan","Jan","Mar","Feb","Jan","Apr","Apr"))
library(shiny)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(selectInput("x","Operations",choices =
c("table"),
multiple=FALSE,selectize = TRUE),
(selectInput("ColC","Choices from ColC", choices = as$ColC,
multiple=TRUE,selectize = TRUE))),
mainPanel(h6("Here it is"),
dataTableOutput("message")
)
)
)
server <- function(input, output, session) {
r1 <- reactive({
if(input$x == "table")
{
tab <- as.data.frame.matrix(table(as$ColC, as$ColA))
tab <- tab[rownames(tab) %in% input$ColC, ]
}
})
output$message <- renderDataTable({
datatable(r1(), rownames = TRUE)
})
}
shinyApp(ui, server)