Joseph Kigotho
Joseph Kigotho

Reputation: 299

Allowing multiple numbers in one numericInput in shiny

I'm trying to have users specify variable breaks as inputs to be supplied to cut function

For fixed breaks, the below code works by accepting one numeric input and cutting the column into chunks of the specified width. I however want this to be variable, such that one can choose any number of breaks. Below is my shiny code.


ui <- fluidPage(
  numericInput("breaks", "Breaks:", 5, min = 1, max = 100),
  dataTableOutput("data")
)
server <- function(input, output) {
  data <- reactive({
    data <- data.frame(A = seq(1:100))
    data$Result <- cut(data$A, breaks = c(0, 5, 8, 15, 100))
    data$Result2 <- cut(data$A, breaks = seq(0, 100, by = input$breaks))
    data
  })

 output$data <- renderDataTable(data())
}
shinyApp(ui, server)

Which is the easiest way to have users enter variable breaks (e.g 0,5,8,15,100 in my code example) and supply the same to the cut function to obtain a new column similar to my Result column?

Upvotes: 2

Views: 2904

Answers (1)

K. Rohde
K. Rohde

Reputation: 9676

This is totally up to your creativity and a pure question of problem solving. There can be literally hundreds of ways to solve that problem.

Below is one solution that lets you insert comma separated values to define the breaks.

But you could also look into creating a dynamic number of numeric inputs.

library(shiny)

ui <- fluidPage(
  textInput("breaks", "Breaks", placeholder = "Enter values separated by a comma..."),
  textOutput("breakresult"),
  dataTableOutput("data")
)
server <- function(input, output) {
  data <- reactive({
    nums <- extract(input$breaks)

    data <- data.frame(A = seq(1:100))
    data$Result <- cut(data$A, breaks = c(0, 5, 8, 15, 100))

    if (!anyNA(nums) && length(nums) >= 2) {
      data$Result2 <- cut(data$A, breaks = nums)
    }

    data
  })

  extract <- function(text) {
    text <- gsub(" ", "", text)
    split <- strsplit(text, ",", fixed = FALSE)[[1]]
    as.numeric(split)
  }

  output$breakresult <- renderText({

    nums <- extract(input$breaks)

    if (anyNA(nums)) {
      "Invalid input"
    } else {
      paste(c("Breaks:", paste(nums, collapse = ", ")), collapse = " ")
    }
  })

  output$data <- renderDataTable(data())
}
shinyApp(ui, server)

Upvotes: 3

Related Questions