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)