通过R/Shiny中的selectInput()传递变量名时出现问题 [英] Problem passing variable names via selectInput() in R/Shiny

查看:404
本文介绍了通过R/Shiny中的selectInput()传递变量名时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Shinyapp,我将其中的变量名作为参数使用selectInput()小部件传递给服务器.以下静态示例说明了我要显示的图:

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

请明确说明,这是上述情节的图像

我想在我的Shinyapp中做的是通过用户可以通过selectInput()选择的不同变量来分隔绘制的分布.但是,当我用通用参数替换上面的var1时,这不是我所得到的.请参见示例:

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)

我得到的实际输出是 与静态示例不同我从(点击进入图像)开始.

有人可以指出我的错误吗?感谢您的帮助.

解决方案

input$var是一个字符串.因此,

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

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.

解决方案

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
})

这篇关于通过R/Shiny中的selectInput()传递变量名时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆