Skip to content

Instantly share code, notes, and snippets.

@stla
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stla/9033053 to your computer and use it in GitHub Desktop.
Save stla/9033053 to your computer and use it in GitHub Desktop.
Shiiny: two selectInput with mutual exclusion
library(shiny)
runApp(
list(ui=pageWithSidebar(
headerPanel("Column Selector - first idea"),
sidebarPanel(
uiOutput("dyncolumns")
),
mainPanel(
tableOutput("subset"),
verbatimTextOutput("count")
)
),
server=function(input, output, session) {
# UI columns
output$dyncolumns <- renderUI({
Colnames <- names(mtcars)
list(
selectInput("x", "x", choices=Colnames, selected=Colnames[1]),
selectInput("y", "y", choices=Colnames, selected=Colnames[2])
)
})
################################################
#### handles selection of identical columns ####
################################################
##
# call Ex the event: x is set to the same value as y, and Ey the symmetric event
##
# REACTIVE VALUES :
R <- reactiveValues(oldx=0, oldy=0)
# oldx: the previous value of x when Ex occurs
# oldy: the previous value of y when Ey occurs
# REACTIVE VALUES :
XY <- reactiveValues(x=NULL, y=NULL, count=0)
# x: the effective value of x
# y: the effective value of y
# count: count each time x=y ('always 0' = 'app successful')
observe({
if(!is.null(XY$x) && !is.null(XY$y)) XY$count <- isolate(XY$count) + (XY$x==XY$y)
})
output$count <- renderText({ XY$count })
##
#
# 1) the case of Ex
#
observe({
if(!is.null(input$y)){
R$oldx <- isolate(input$x)
}
})
observe({
if(!is.null(input$x)){
if(input$x!=isolate(input$y)){
R$oldx <- input$x
XY$x <- input$x; XY$y <- isolate(input$y)
}
else{ # Ex occurs then we exchange x and y
oldx <- isolate(R$oldx)
updateSelectInput(session, "y", choices=names(mtcars), selected=oldx)
XY$x <- input$x; XY$y <- oldx
}
}
})
##
#
# 2) the case of Ey
#
observe({
if(!is.null(input$x)){
R$oldy <- isolate(input$y)
}
})
observe({
if(!is.null(input$y)){
if(input$y!=isolate(input$x)){
R$oldy <- input$y
XY$x <- isolate(input$x); XY$y <- input$y
}
else{ # Ey occurs then we exchange x and y
oldy <- isolate(R$oldy)
updateSelectInput(session, "x", choices=names(mtcars), selected=oldy)
XY$x <- oldy; XY$y <- input$y
}
}
})
#################
## Subset data ##
#################
output$subset <- renderTable({
if(!is.null(input$x)) head(subset(mtcars, select=c(XY$x,XY$y)))
})
}
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment