Reputation: 1265
I am subsetting a dataframe in R shiny using the following example
if (interactive()) {
ui <- fluidPage(
selectInput("variable", "Variable:",
c("Cylinders" = "cyl",
"Transmission" = "am",
"Gears" = "gear")),
tableOutput("data")
)
server <- function(input, output) {
output$data <- renderTable({
mtcars[, c("mpg", input$variable), drop = FALSE]
}, rownames = TRUE)
}
shinyApp(ui, server)
}
This works with a predetermined set of columns
I have written the following code with a slider to create inputs that will act as column numbers for the MTcars dataset used in the above example. Is there a way to use the number indicated on th slider a an input for the column number and dynamically subset the dataframe in shiny
I have written the folowing code but it doesn't seem to work
if (interactive()) {
ui <- fluidPage(
sliderInput(inputId = "slider1", label = "numberinput", min = 1, max = 10,
value = 1, step = 1),
selectInput(inputId = "Columnno", label = "Column Number",choices =
as.numeric(input$slider1)),
tableOutput("data")
)
server <- function(input, output) {
output$data <- renderTable({
mtcars[, c("mpg", input$Columnno), drop = FALSE]
}, rownames = TRUE)
}
shinyApp(ui, server)
}
I request some guidance in this regard.
Upvotes: 0
Views: 53
Reputation: 29417
IF you want just one extra column you can do this:
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "slider1", label = "numberinput", min = 1, max = 10, value = 1, step = 1),
selectInput(inputId = "Columnno", label = "Column Number",choices = NULL,selected = NULL),
tableOutput("data")
)
server <- function(input, output,session) {
observeEvent(input$slider1,{
updateSelectInput(session,"Columnno",choices = as.numeric(1:input$slider1), selected = as.numeric(input$slider1))
})
output$data <- renderTable({
req(input$Columnno)
mtcars[, c("mpg", colnames(mtcars)[as.numeric(input$Columnno)]), drop = FALSE]
}, rownames = TRUE)
}
shinyApp(ui, server)
Upvotes: 2