Skip to content

Instantly share code, notes, and snippets.

@xezpeleta
Created June 14, 2018 18:23
Show Gist options
  • Save xezpeleta/ea75d2e1e3ded0aebe8b0f5b238cf0d8 to your computer and use it in GitHub Desktop.
Save xezpeleta/ea75d2e1e3ded0aebe8b0f5b238cf0d8 to your computer and use it in GitHub Desktop.
R and Shiny, linked selectInputs
library(shiny)
# Just to use msleep dataset
library(ggplot2)
# Remove NAs
msleep = msleep[complete.cases(msleep), ]
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
h1("Animal's sleep"),
h3("Choose animal type:"),
selectizeInput(inputId = "animaltype",
label = "Type:",
c (msleep$vore),
options = list(onInitialize = I('function() { this.setValue("omni"); }'))),
h3("Choose your animal:"),
# This selectInput will be updated by the server!
selectizeInput(inputId = "animalname",
label = "Animal:",
c (msleep$name))
),
mainPanel(
plotOutput(outputId = "distPlot")
),
)
)
server <- function(input,output,session){
# Update "animalname"
observe({
animaltype <- input$animaltype
updateSelectInput(session, "animalname", choices = msleep$name[msleep$vore == animaltype])
})
output$distPlot <- renderPlot({
# He tenido que construir la tabla de esta forma!! :S
# Mi intención era pasar al barplot algo como esto:
#
# Nombres = names(msleep)[6:9]
# Valores = msleep[grep("Cow", msleep$name),6:9]
#
# Pero lo segundo me dice que no es un objeto de tipo vector/matrix...
sleep_total = msleep$sleep_total[grep(input$animalname, msleep$name)]
sleep_rem = msleep$sleep_rem[grep(input$animalname, msleep$name)]
sleep_cycle = msleep$sleep_cycle[grep(input$animalname, msleep$name)]
awake = msleep$awake[grep(input$animalname, msleep$name)]
y = data.frame(Sleep=c('Sleep total','Sleep rem','Awake'),
Hours=c(sleep_total, sleep_rem, awake))
color <- c("#4FC3F7", "#AED581", "#FFF176")
barplot(y$Hours,
names.arg=y$Sleep,
main = input$animalname,
ylab = "Hours",
xlab = "Sleep",
ylim = range(c(0,24)),
col = color
)
})
}
shinyApp(ui=ui, server=server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment