Home > Software engineering >  how to pass an input value in R Studio in this case?
how to pass an input value in R Studio in this case?

Time:12-17

If I run my code in this case, it works, known that the input is yet not passed. the code simply makes dataframe out of a data.csv. this datframe has many the following columns code , vaccinationsTotal , peopleFirstTotal , peopleFullTotal , peopleBoosterTotal and what I am trying to do is just select the column through the input$sel

library(shiny)
library(dplyr)
library(ggplot2)
library(magrittr)


library(readr)
dataf <- read_csv("data.csv")


server <- function(input, output, session) {
 #Summarize Data and then Plot 
data <- reactive({
    req(input$sel)
     df <- dataf %>%  group_by(code) %>% summarise(vaccinationsTotal)
    print(df)
  })
  
  #Plot 
  output$plot <- renderPlot({  
   
    g <- ggplot(data(), aes( y = vaccinationsTotal  ,x = code) ) 
    g   geom_bar( stat = "sum")
  
  })
}

ui <- basicPage(
  
  selectInput(inputId = "sel",
              label = "eine möglichkeit auswählen",
             
               list("vaccinationsTotal","peopleFirstTotal","peopleFullTotal","peopleBoosterTotal")),
 
   plotOutput("plot")
)

shinyApp(ui = ui, server = server)

if I run my code after replacing summarise(vaccinationsTotal) with summarise(input$sel) it shows me the ylim just with one value which is vaccinationsTotal


 df <- dataf %>%  group_by(code) %>% summarise(vaccinationsTotal)
    print(df)
  })
  
  #Plot 
  output$plot <- renderPlot({  
   
    g <- ggplot(data(), aes( y = vaccinationsTotal  ,x = code) ) 
    g   geom_bar( stat = "sum")
   

How can I pass an input variable in this case ? I spent days trying things.

CodePudding user response:

You have made 3 mistakes in your code.

  1. You are passing input$sel to summarise. What you need to pass is `get(input$sel).

  2. The other thing is when you summarise the data in R, it uses the column name of the data that you are summarising. So, in your case, while plotting the data, you need to pass the same column name to the y-axis of the ggplot.

Or you can just rename the column while summarising it. Like this:

summarise(output = get(input$sel))

  1. Now, you just need to change the variable name that you are passing, to the name variable name that you used while renaming in summarise function.
server <- function(input, output, session) {
  #Summarize Data and then Plot 
  data <- reactive({
    req(input$sel)
    df <- dataf %>%  
      group_by(code) %>% 
      summarise(output = get(input$sel))
    print(df)
  })
  
  #Plot 
  output$plot <- renderPlot({  
    g <- ggplot(data(), aes(y = output, x = code) ) 
    g   geom_bar( stat = "sum")
    
  })
}

Please note that doing this will show output as your y-axis label. Although you can tweak it inside the ggplot function.

  • Related