0

In shiny, is there a way to put a input variable as parameter . For example,

below is the function to create a ggplot. It has 2 parameter dt and x_axis. dt = dataframe object x_axis = categorical value that depends on user selection (input$var).Input$var contains c("A", "B")

fun_sam <- function(dt, x_axis) {
  dt1 <- dt %>% dplyr::group_by({{get(x_axis)}}, `Se`) %>% dplyr::summarise(Weight = sum(`Mar`))
  dt1 <- as.data.frame(dt1)
  return(ggplot(dt1, aes(x = {{get(x_axis)}}, y = Weight, fill = `Se`)) +
           geom_bar(width = 1, stat = "identity") +
           theme_bw() +
           theme(panel.border = element_blank()) +
           theme(panel.grid = element_blank()) +
           theme(axis.text.x = element_text(angle = 45))) 
}

So when the below is code, i should get the output based on user selection but currently it is not happening

fun_sam(asd, input$var)    #### Not working

but this is working

fun_sam(asd, A)    #### working

below is the entire application

library(shiny)
library(dplyr)

ui <- fluidPage(
  selectInput("var", "Sel", choices = c("A", "B"), selected = "A"),
  plotlyOutput("sd")
)

server <- function(input, output, session) {
  
  dsa <- data.frame(A = c("x","y","z"), B = c("x1","y1","z1"), Se = c("d","d", "f"), x = c(3,4,5))
  fun_sam <- function(dt, x_axis) {
    dt1 <- dt %>% dplyr::group_by(!!sym(x_axis), `Se`) %>% dplyr::summarise(Weight = sum(`x`))
    dt1 <- as.data.frame(dt1)
    return(ggplot(dt1, aes(x = !!sym(x_axis), y = Weight, fill = `Se`)) +
             geom_bar(width = 1, stat = "identity") +
             theme_bw() +
             theme(panel.border = element_blank()) +
             theme(panel.grid = element_blank()) +
             theme(axis.text.x = element_text(angle = 45))) 
  }
  
  ### not working
  output$sd <- renderPlotly({
    fun_sam(dsa, get(input$var))
    
  })
  
  
  ### working
  # output$sd <- renderPlotly({
  #   fun_sam(dsa, A)
  #   
  # })
}

shinyApp(ui, server)
manu p
  • 952
  • 4
  • 10
  • Does this answer your question? [How to connect user input with gganimate graph in R shiny?](https://stackoverflow.com/questions/71810703/how-to-connect-user-input-with-gganimate-graph-in-r-shiny) – Limey Jun 10 '22 at 09:33
  • I tried. But not working. I have edited my question here. Please refer – manu p Jun 10 '22 at 09:45
  • Try again. As stated in the question I have linked to, replace `{{x_axis}}` with `!! sym(x_axis)`. Twice. When I do it, the modified code produces sensible output. – Limey Jun 10 '22 at 09:51
  • 2
    Change `fun_sam(dsa, get(input$var))` to `fun_sam(dsa, input$var)` – YBS Jun 10 '22 at 11:37

0 Answers0