Get min max of sliderInput in shiny
After reading the two answers, I feel that the solution would be to pass an extra argument to my module containing the min/max
values. Overall, the ui.R
renders finally to html
and I am not sure whether conceptually you should even try to access the html
from the server.R
Can I set the min and max values that a sliderInput will have when a Shiny app starts?
The value
needs to be set to c(min(vector1), max(vector1))
instead of the whole vector1
:
sliderInput(
inputId = 'slider1',
label = 'Select value',
min = min(vector1),
max = max(vector1),
value = c(min(vector1), max(vector1)),
step = (max(vector1)-min(vector1))/5
)
The assignment of the input to a variable has also been removed because, as latlio pointed out, it might cause namespacing issues.
shiny sliderInput from max to min
EDIT 2017-10-13: This function is now available in package shinyWidgets
(with a different name : sliderTextInput()
).
Hi you can write your own slider function like this (it's a little dirty...) :
sliderValues <- function (inputId, label, values, from, to = NULL, width = NULL) {
sliderProps <- shiny:::dropNulls(list(class = "js-range-slider",
id = inputId,
`data-type` = if (!is.null(to)) "double",
`data-from` = which(values == from) - 1,
`data-to` = if (!is.null(to)) which(values == to) - 1,
`data-grid` = TRUE,
`data-values` = paste(values, collapse = ", ")
))
sliderProps <- lapply(sliderProps, function(x) {
if (identical(x, TRUE))
"true"
else if (identical(x, FALSE))
"false"
else x
})
sliderTag <- div(class = "form-group shiny-input-container",
style = if (!is.null(width))
paste0("width: ", validateCssUnit(width), ";"),
if (!is.null(label))
shiny:::controlLabel(inputId, label), do.call(tags$input,
sliderProps))
dep <- list(htmltools::htmlDependency("ionrangeslider", "2.0.12", c(href = "shared/ionrangeslider"),
script = "js/ion.rangeSlider.min.js",
stylesheet = c("css/ion.rangeSlider.css",
"css/ion.rangeSlider.skinShiny.css")))
htmltools::attachDependencies(sliderTag, dep)
}
The point to do this is to use the values
attribute from ionrangeslider (see section Using custom values array here)
The downside is the value of the input you retrieve server-side isn't the value of the slider but the index of the value (starting from 0).
You can use this function like this :
library("shiny")
runApp(
list(
ui = fluidPage(
# you have to pass the values you want in the slider directly to th function
sliderValues(inputId = "test", label = "", from = 5, values = 5:1),
verbatimTextOutput(outputId = "slidervalue")
),
server = function(input,output) {
output$slidervalue <- renderPrint({
# Careful ! : input$test isn't the expected value !!!
(5:1)[input$test + 1]
})
}
)
)
And bonus : it works with characters vectors too :
runApp(
list(
ui = fluidPage(
sliderValues(inputId = "test", label = "", from = "g", to = "o", values = letters),
verbatimTextOutput(outputId = "slidervalue")
),
server = function(input,output) {
output$slidervalue <- renderPrint({
# Careful ! : input$test isn't the expected value !!!
letters[input$test + 1]
})
}
)
)
shiny sliderInput range minimum and maximum values
This works for me:
library(shiny)
runApp(list(ui = fluidPage(
mainPanel(sliderInput("test", "Select values", value= c(.001,.9), min= 0.0001, max= 1)),
verbatimTextOutput("test2")
),
server = function(input, output, session) {
output$test2 <- renderPrint(min(input$test))
}))
I'm guessing your problem is somewhere in the code you haven't shown us. Can you give the code for the entire running example of your problem?
sliderInput `min`, `max` and `value` NULL problem in R Shiny App
Seems that shiny::sliderInput
expects explicit values instead of R expressions. However, you can set dummy values for e.g. max and min and then update them with the real data at the very beginning of the server function. Here is a more minimal example:
library(shiny)
# Create sample data
Date <- c(
"2014-04-08", "2014-06-04", "2014-04-30",
"2014-05-30", "2014-05-01"
)
id <- as.numeric(c("1", "2", "3", "4", "5"))
# Create a df from the above columns
df <- data.frame(id, lat, lon, Date)
df$Year <- lubridate::year(df$Date)
df$Month <- lubridate::month(df$Date, label = TRUE, abbr = FALSE)
df$Week <- lubridate::week(df$Date)
df$Date <- as.Date(df$Date)
ui <- fluidPage(
sliderInput("Input_2",
label = "Please select a weekly range",
step = 1,
# init with dummy values
min = 0, max = 1,
value = 1
)
)
server <- function(input, output, session) {
updateSliderInput(session, "Input_2",
min = min(df$Week), max = max(df$Week),
value = unique(df$Week)
)
}
shinyApp(ui = ui, server = server)
r shiny sliderInput with exact values instead of evenly divided range
I think the sliderTextInput
from shinyWidgets
does what you want. Though on the slider, all values are equally separated and not proportionnally.
library(shiny)
library(shinyWidgets)
ui <- fluidPage(
sliderTextInput(
inputId = "myslider",
label = "Choose a value:",
choices = c(2,3,5,7,11,13,17,19,23,29,31),
grid = TRUE
)
)
server <- function(input, output, session) {
observe(print(input$myslider))
}
shinyApp(ui, server)
Shiny Dynamic sliderInput displaying warning when min and max dates are dynamically generated from other UIs
Overview
The main issue here is that when the app is initialized first_filter()$Date
is NULL, as you set it in first_filter <- reactive(...)
. This can be fixed by placing a req(first_filter())
in output$dyn_slider <- renderUI(...)
as shown below.
req()
is the preferred method to check if inputs and reactive variables are available. It tests for "truthy-ness". Even though the rest of the code works, as a best practice I would recommend you change it to use req()
instead of,
if(is.null(input$sample)) {
return(NULL)
}
Fixed Code
# Define UI for application
ui <- dashboardPage(
# Application title
dashboardHeader(title = "App"),
# Dashboard Sidebar
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "data_tab")
)
),
dashboardBody(
tabItems(
tabItem(tabName = "data_tab",
fluidRow(
box(
selectInput("Group_selector",
"Select Group",
choices = unique(df$Group)),
# Add a UI Output to select Subgroup and Date range
uiOutput("dyn_metric"),
uiOutput("dyn_slider")
),
box(
# Produce output using plotly
plotlyOutput("plot")
)
)
)
)
)
)
library(shiny)
library(shinydashboard)
library(dplyr)
library(plotly)
library(lubridate)
# Define server logic required to plot trend
server <- function(input, output) {
# Render a UI for selecting of Subgroup metric
output$dyn_metric <- renderUI({
selectInput("Subgroup_selector",
"Select Subgroup", choices = unique(df[df$Group == input$Group_selector, "Subgroup"]))
})
# Render a UI for selecting date range
output$dyn_slider <- renderUI({
req(first_filter())
sliderInput("date_range_selector", "Select Date Range",
min = min(year(first_filter()$Date)),
max = max(year(first_filter()$Date)),
value = c(max(year(first_filter()$Date)-1),
max(year(first_filter()$Date))),
sep = "")
})
# Filter by Group and Subgroup first
first_filter <- reactive({
if(is.null(input$Subgroup_selector)) {
return(NULL)
}
df %>%
filter(Group == input$Group_selector & Subgroup == input$Subgroup_selector)
})
# Filter by Date Range next
second_filter <- reactive({
if(is.null(input$date_range_selector)) {
return(NULL)
}
first_filter() %>%
filter(between(year(Date), input$date_range_selector[1], input$date_range_selector[2]))
})
# Render plot using second filtered dataset
output$plot <- renderPlotly({
if(is.null(second_filter())) {
return()
}
plot_ly(second_filter(), x = ~Date, y = ~Value, type = "scatter", mode = "lines+markers")
})
}
# Run the application
shinyApp(ui = ui, server = server)
Max and min in a sliderinput that changes according to the column that I choose
EDIT: Including some NA
s in the indices. Perhaps you can try this
Indicea<-c(1,2,3,5,3,1,3,5,3,6,NA,2,1,1,3,2)
Indiceb<-c(12,15,12,14,13,16,14,13,15,12,14,13,NA,13,11,12)
Indicec<-c(100,NA,120,154,125,201,102,150,102,105,140,156,118,113,175,189)
Indiced<-c(0.1,0.5,06,032,0.1,0.25,0.23,0.12,0.15,NA,
0.25,0.45,1.0,0.5,0.26,0.45)
Especialidad<-c("gato","gato","gato","perro","perro","perro","perro",
"buho","buho","buho","buho","tigre","tigre","tigre",NA,"tigre")
data <- data.frame(Indicea, Indiceb,Indicec,Indiced,Especialidad)
ui <- fluidPage(
tabItem("IndicesI",
tabsetPanel(# position= "left",
tabPanel("Indices de ingreso", icon = icon("file-medical-alt"),
sidebarLayout(sidebarPanel(
uiOutput("SeleccioneEspecialidad2"),
uiOutput("SeleccioneIndice"),
uiOutput("Rango"),
checkboxInput("Todas","Seleccione Todas/Ninguna", value = FALSE)
),
mainPanel(
plotOutput("lineplotI"),
dataTableOutput("summary9")
)))
)
)
)
server <- function(input, output, session) {
output$SeleccioneEspecialidad2<-renderUI({
choices <- na.omit(data$Especialidad)
selectInput("SeleccioneEspecialidad2", "Seleccione Especialidad",
choices=choices, multiple = T, selected = TRUE )
})
BD<-reactive({
req(input$SeleccioneEspecialidad2)
data %>%
filter(Especialidad %in% input$SeleccioneEspecialidad2 )
})
output$SeleccioneIndice <-renderUI({
selectInput("SeleccioneIndice", "Seleccione Indice", choices=
c("Ments"="Indicea",
"Fragilidad"="Indiceb",
"ElixhauserAHRQ"="Indicec",
"ElixhauserVanWalraven"="Indiced"))
})
output$Rango<-renderUI({
req(input$SeleccioneIndice)
minn <- min(BD()[,input$SeleccioneIndice], na.rm = TRUE)
maxx <- max(BD()[,input$SeleccioneIndice], na.rm = TRUE)
valu <- minn + (maxx - minn)/2
sliderInput("Rango",label = "Seleccione un rango", min = minn, max=maxx, value=valu)
})
}
shinyApp(ui, server)
Access sliderInput range
It is possible using jQuery and the shinyjs
package (to execute the jQuery). You need to write a custom function that retrieves the currently set max value (getMax
in below example). If your slider is wrapped in a div with a fixed title mySlider
, you can let jQuery find that slider:
$('#mySlider .irs-max').text());
returns the currently set max. I use a button to execute that function and alert the currently set max:
library(shiny)
library(shinyjs)
jQuery_max_code <- "shinyjs.getMax = function(){alert($('#mySlider .irs-max').text());}"
ui <- fluidPage(
mainPanel(
# make the function getMax() available to the browser
useShinyjs(),
extendShinyjs(text=jQuery_max_code),
# providing the slider an id so I can access it with jQuery: mySlider
div(id = "mySlider", sliderInput("mySlider","Slider:", min = 1, max = 50, value = 30)),
# a slider to change the max of our slider
sliderInput("maxSlider","Max Value of above slider:", min = 1, max = 200, value = 30),
# a button to alert the current max of mySlider
actionButton("button", "Print slider maximum value")
)
)
server <- function(input, output, session) {
# change value of mySlider
observeEvent(input$maxSlider, {
updateSliderInput(session, "mySlider", max=input$maxSlider)
})
# alert the current max after button click
observeEvent(input$button, {
js$getMax()
})
}
shinyApp(ui = ui, server = server)
Related Topics
Axis-Labeling in R Histogram and Density Plots; Multiple Overlays of Density Plots
Is There More Efficient or Concise Way to Use Tidyr::Gather to Make My Data Look 'Tidy'
R How Many Element Satisfy a Condition
R Mlogit Model, Computationally Singular
Fill in Gaps (E.G. Not Single Cells) of Na Values in Raster Using a Neighborhood Analysis
How to Efficiently Retrieve Top K-Similar Vectors by Cosine Similarity Using R
Add Geom_Line to Link All The Geom_Point in Boxplot Conditioned on a Factor with Ggplot2
Initialize a List of Matrices in R
Create Group Based on Fuzzy Criteria
How Does R Represent Na Internally
Standard Deviation on Dataframe Does Not Work
Ggplot2: Shape, Color and Linestyle into One Legend
Ggplot2 Ggsave Function Causes Graphics Device to Not Display Plots
How to Generate Multivariate Random Numbers with Different Marginal Distributions