Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shiny - Changing Variables on a Plot Based on User Input

Tags:

r

shiny

I have a data set that looks like the following:

Win    Gender    Score (1-4)    Weight     SHE
1      F         2              140        Y
0      M         3              155        Y
1      M         4              134        N

I am creating a Shiny App that will create side by side bar charts for the rows that belong to the different scores (4 groups). I want the user to be able to select the variable that will be on the x-axis (either Win, Gender of SHE), and have the charts update to reflect the counts of that variable within each group.

I have tried the following code in server.R:

shinyServer(function(input, output){
     output$plotOne <- renderPlot({
ggplot(data=GroupOne, aes(x=input$var))+geom_bar(stat='bin')
})
})

'var' is the name that I have specified for the variable the user selects based on the radio button input in ui.R. The error message I am getting is that input is not found.

I have also tried the above code, but with

histogram(~input$var, data=GroupOne). 

This resulted in errors about negative length vectors and other things.

like image 780
Megan Avatar asked Mar 18 '26 20:03

Megan


1 Answers

Try using a reactive function to tie the input into your data frame:

server <- function(input, output) {

  data <- reactive({
if ( "Win" %in% input$var) return(your_data_frame$Win)
if ( "Gender" %in% input$var) return(your_data_frame$Gender)
if ( "Score" %in% input$var) return(your_data_frame$Score)
if ( "Weight" %in% input$var) return(your_data_frame$Weight)
if ( "SHE" %in% input$var) return(your_data_frame$SHE)
  })

  output$plotOne <- renderPlot({
ggplot(data=GroupOne, aes(x=data()))+geom_bar(stat='bin')
  })
}
like image 115
Renel Chesak Avatar answered Mar 20 '26 11:03

Renel Chesak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!