【问题标题】:R shiny error: Cannot coerce type 'closure' to vector of type 'double'R闪亮错误:无法将类型“闭包”强制为“双”类型的向量
【发布时间】:2013-12-24 04:11:20
【问题描述】:

我想将一个数字向量作为输入,然后简单地绘制直方图。这是我的 R 代码:

ui.R:

library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Hello Shiny!"),

  sidebarPanel(selectInput("Vector", "Select Numbers", c(1,2,3,4), selected = NULL, multiple = TRUE)),

  mainPanel( plotOutput("plotVector"))
))

服务器.R:

library(shiny)
shinyServer(function(input, output) {

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

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

})

运行应用的代码:

library(shiny)
runApp("C:/Users/me/Desktop/R Projects/testShiny")

当我运行此程序时,我收到错误“无法将类型 'closure' 强制转换为 'double' 类型的向量”

你能帮忙吗?谢谢。

【问题讨论】:

  • “闭包”是一个函数——在某个地方,您调用了一个函数(按名称)而不是某个变量。
  • 那么我如何从函数而不是函数本身返回数据?有什么想法吗?谢谢。

标签: r


【解决方案1】:

在服务器端,你将 v 定义为一个函数:

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

然后您尝试将其用作as.numeric(...) 的参数:

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

所以 R 正试图将一些 class: function 转换为 double。

编辑:回答 OP 的后续问题。对于 ui.R 和 server.R 使用以下内容:

在服务器端,shinyUI(...) 采用两个自动传递的对象:inputoutputinput(R 术语中的“列”)的属性在 ui.R 中通过创建各种 GUI 对象来定义。因此,您通过调用selectInput(...) 创建了一个select 对象。对象的 id 是"Vector"。这在服务器端被引用为:input$Vector。请注意,您调用的 Vector 实际上是一个数字:用户在选择框中选择的任何内容。绘制单个数字的直方图是没有意义的,所以我更改了代码以使 input$Vector 成为正态分布的平均值。您还遇到了 input$Vector 在代码中被初始化为 NULL 的问题,这引发了错误。所以我把它改成初始化为0。

声明:

output$mainplot <- ...

服务器端在ui.R中填充一个对象output$main_plot,由语句定义:

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

总结一下,如下:

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

生成这个:

【讨论】:

  • 那么我如何从函数而不是函数本身返回数据?有什么想法吗?谢谢。
  • @user3022875 Jhoward 击败了我,以秒为单位识别错误 :-),但您的问题没有抓住重点:您需要从函数主体中删除 v&lt;-。然后v(x) 将返回hist 期望的数据向量。
【解决方案2】:

看起来这样做很有效!

library(shiny)
shinyServer(function(input, output) {

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

  output$plotVector <- renderPlot({  
data <- v()
hist(data)
    }) 

})

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 1970-01-01
    • 2015-04-29
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多