无法将类型“closure”强制为类型“character”的向量

无法将类型“closure”强制为类型“character”的向量,r,shiny,R,Shiny,我正在尝试使用shiny创建一个交互式散点图。使用iris数据,我想让用户选择散点图*花瓣与萼片的x和y维度,然后输出所选维度的简单散点图。很简单 首先,我需要构建一个函数,该函数允许我将表示维度的字符串传递给ggplot。我这样做了,并用静态数据进行了测试。很好 接下来,我定义了两个下拉列表和两个后续字符串,使用Shining表示花瓣和萼片尺寸,这是我的x轴和y轴 接下来,我使用switch语句使用shinny的reactive函数设置两个字符串变量 这似乎是出问题的地方 我得到的错误是:错误

我正在尝试使用shiny创建一个交互式散点图。使用iris数据,我想让用户选择散点图*花瓣与萼片的x和y维度,然后输出所选维度的简单散点图。很简单

首先,我需要构建一个函数,该函数允许我将表示维度的字符串传递给ggplot。我这样做了,并用静态数据进行了测试。很好

接下来,我定义了两个下拉列表和两个后续字符串,使用Shining表示花瓣和萼片尺寸,这是我的x轴和y轴

接下来,我使用switch语句使用shinny的reactive函数设置两个字符串变量

这似乎是出问题的地方

我得到的错误是:错误:无法将“closure”类型强制为“character”类型的向量

我已经采取了许多步骤来调试我的代码。我首先在代码输出$myplot=renderPlot{myplotfunct

这很好。情节呈现得和我预期的一样

然后,我添加了一个调试行来跟踪传递这个plot函数的字符串的值。宾果。它是空的。为什么它是空的?似乎应该从UI.r文件传递一个值

代码如下

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

用户界面

服务器.R


最后两行中对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())})
允许您获取被动元素的值,而不是与被动元素本身交互。这是一个非常基本的概念,如果您还不熟悉,请重新访问

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


您是否需要在myplotfunct调用中使用datasetInput1、datasetInput2?此答案解决了此特定问题,但没有告诉我根本原因。请重新阅读:如果您不将
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)})

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

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