Problem passing variable names via selectInput() in R/Shiny

筅森魡賤 提交于 2020-01-16 18:22:33

问题


I'm building a shinyapp where I am passing variable names as arguments to the server with the selectInput() widget. The following static example illustrates the plot that I want displayed:

  g <- ggplot(d, aes(y, fill = var1, colour = var1)) + 
    geom_density(alpha=.2) 

Just to be clear, here is an image of the above plot

What I want to do in my shinyapp is to separate the plotted distributions by different variables that the user can choose via selectInput(). But when I substitute var1 in the above with a generic argument, this is not what I get. Please see the example:

library(ggplot2)
library(shiny)

d <- data.frame(var1=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
                var2=as.factor(sample(x = 1:4, size = 250, replace = TRUE)),
                y=rnorm(250, mean = 0, sd = 1))

nms <- names(d)

ui <- fluidPage(selectInput(inputId ="var", "Variable:",
                            choices = nms, selected = "var1"),
                plotOutput(outputId = "plot")
)

server <- function(input, output) {

  g <- ggplot(d, aes(y, fill = input$var, colour = input$var)) + 
    geom_density(alpha=.2) 


  output$plot <- renderPlot(g)

}

shinyApp(ui,server)

The actual output I get is different from the static example I started with (click through for image).

Can someone please point out my error? Thankful for help.


回答1:


input$var is a string. Therefore, do

output$plot <- renderPlot({
  g <- ggplot(d, aes_string("y", fill = input$var, colour = input$var)) + 
         geom_density(alpha=.2)
  g
})


来源:https://stackoverflow.com/questions/53896619/problem-passing-variable-names-via-selectinput-in-r-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!