【问题标题】:cannot coerce type 'closure' to vector of type 'character'不能将类型“闭包”强制为“字符”类型的向量
【发布时间】:2015-07-01 00:00:36
【问题描述】:

我正在尝试使用闪亮构建交互式散点图。使用 iris 数据,我想让用户选择散点图 *petal vs sepal) 的 x 和 y 维度,然后输出所选维度的简单散点图。很简单。

首先,我需要构建一个函数,允许我将表示尺寸的字符串传递给 ggplot。我这样做并用静态数据对其进行了测试。工作正常。

接下来,我为花瓣和萼片尺寸(这些是我的 x 和 y 轴)定义两个下拉列表和两个后续字符串(使用闪亮)。

接下来我使用shiny 的reactive() 函数使用switch 语句设置两个字符串变量。

这似乎是出了问题的地方。

我得到的错误是:错误:无法将“闭包”类型强制转换为“字符”类型的向量

我已经采取了一些步骤来调试我的代码。我首先将硬编码尺寸(例如“Petal.Length”)插入代码的最后一行 output$myplot = renderPlot({myplotfunct( ...

这很好用。情节按照我的预期呈现。

然后我添加了一个调试行来跟踪我正在传递这个绘图函数的字符串的值。答对了。它是空的。为什么它是??似乎应该从 UI.r 文件中传递一个值。

代码如下。

任何帮助将不胜感激。谢谢!

UI.R

library(shiny)

# Define UI for dataset viewer application
shinyUI(fluidPage(

# Application title
titlePanel("Shiny Text"),

# Sidebar with controls to select a dataset and specify the
# number of observations to view
sidebarLayout(
  sidebarPanel(
    selectInput("dataset1", "Choose a Sepal Measure:", 
              choices = c("Sepal Length", "Sepal Width")),

    selectInput("dataset2", "Choose a Petal Measure:", 
              choices = c("Petal Length", "Petal Width"))
 ),

 # Main Scatter Plot
 mainPanel(

   textOutput("testvar"),

   plotOutput("myplot")
   )
  )
))

Server.R

library(shiny)
library(datasets)

library(ggplot2)

#Define a function to plot passed string variables in ggplot

myplotfunct = function(df, x_string, y_string) {
  ggplot(df, aes_string(x = x_string, y = y_string)) + geom_point()
}

shinyServer(function(input, output) {

# Sepal Inputs
datasetInput1 <- reactive({
  switch(input$dataset1,
       "Sepal Length" = "Sepal.Length",
       "Sepal Width" = "Sepal.Width")
})

# Petal Inputs
datasetInput2 <- reactive({
  switch(input$dataset2,
       "Petal Length" = "Petal.Length",
       "Petal Width" = "Petal.Width")
})

#Debug print value of sting being passed
output$testvar = renderText(print(datasetInput1))

# Plot
output$myplot = renderPlot({myplotfunct(iris, datasetInput1, datasetInput2)})

})

【问题讨论】:

  • 您需要在myplotfunct() 通话中使用datasetInput1(), datasetInput2() 吗?

标签: r shiny


【解决方案1】:

最后两行对 datasetInput1 和 datasetInput2 的调用是错误原因。

您应该改为调用 datasetInput1() 和 datasetInput2()。 否则,R 会尝试将函数转换为 char。应该是:

#Debug print value of sting being passed
output$testvar = renderText(print(datasetInput1()))

# Plot
output$myplot = renderPlot({myplotfunct(iris, datasetInput1(), datasetInput2())})

() 允许您获取反应元素的值,而不是与反应元素本身进行交互。这是 Shiny 的一个非常基本的概念,如果您还不熟悉,也许可以重新访问 shiny tutotial

只需添加(),错误就会消失,如下所示:

【讨论】:

  • 这个答案解决了这个具体问题,但没有告诉我根本原因是什么。
  • 请再读一遍:“R试图将函数转换为char”如果你不放()
猜你喜欢
  • 2019-05-23
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
相关资源
最近更新 更多