R shiny error: Cannot coerce type 'closure' to vector of type 'double'

后端 未结 2 738
醉酒成梦
醉酒成梦 2020-12-09 20:55

I would like to take in a vector of numbers as input and then simply plot the histogram. Here is my R code:

ui.R:

library(shiny)

shinyUI(pageWithSid         


        
相关标签:
2条回答
  • 2020-12-09 21:15

    On the server side, you define v as a function:

    v<- function()
     {
      v <- rnorm(input$Vector)#take vector as input
    }
    

    and then you try to use it as the argument to as.numeric(...):

    output$plotVector <- renderPlot({  hist(as.numeric(v))}) 
    

    so R is trying to convert something of class: function to double.

    Edit: to answer OP's followup question. With the following for ui.R and server.R:

    On the server side, shinyUI(...) takes two objects which are passed automatically: input and output. The properties of input ("columns" in R terminology) are defined in ui.R by creating various GUI objects. So you create a select object with a call to selectInput(...). The object's id is "Vector". This is referenced on the server side as: input$Vector. Note that what you are calling Vector is actually a single number: whatever the user selects in the select box. Plotting the histogram of a single number is meaningless, so I changed the code to make input$Vector the mean of a normal distribution. You also had the problem that input$Vector was initialized to NULL in your code, which threw an error. So I changed that to initialize to 0.

    The statement:

    output$mainplot <- ...
    

    on the server side populates an object output$main_plot in ui.R, which is defined by the statement:

    ... plotOutput("main_plot")...
    

    Rolling it all up, the following:

    ui.R:

    library(shiny)
    shinyUI(pageWithSidebar(
      headerPanel("Hello Shiny!"),
      sidebarPanel(selectInput("Vector", "Select Mean of Distribution", c(0,1,2,3,4), selected = 0, multiple = TRUE)),
      mainPanel( plotOutput("main_plot"))
    ))
    

    server.R:

    library(shiny)
    shinyServer(function(input, output) {
      v<- function() {
        return(rnorm(100,mean=as.numeric(input$Vector)))  
      }
      output$main_plot <- 
        renderPlot( 
          hist(v(), breaks=10, xlab="",
               main="Histogram of 100 Samples\n taken from: N[mean, sd=1]")) 
    })
    

    Generates this:

    0 讨论(0)
  • 2020-12-09 21:23

    It looks like doing this works!

    library(shiny)
    shinyServer(function(input, output) {
    
    v<- function()
     {
      v <- rnorm(input$Vector)#take vector as input
    }
    
      output$plotVector <- renderPlot({  
    data <- v()
    hist(data)
        }) 
    
    })
    
    0 讨论(0)
提交回复
热议问题