无法将类型'闭包'强制为类型'字符'的向量。 [英] cannot coerce type 'closure' to vector of type 'character'

查看:47
本文介绍了无法将类型'闭包'强制为类型'字符'的向量。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SHINY构建交互式散点图。使用虹膜数据,我想让用户选择散点图的x和y维度(花瓣与萼片),然后输出所选维度的简单散点图。相当直截了当。

首先,我需要构建一个函数,该函数允许我将表示维度的字符串传递给gglot。我做到了这一点,并用静电数据进行了测试。工作正常。

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

接下来,我使用SHINY的Reactive()函数使用Switch语句设置两个字符串变量。

这似乎是出问题的地方。

我得到的错误是:错误:无法将类型‘Closure’强制为类型‘Character’的向量

我采取了许多步骤来调试我的代码。我首先插入了硬编码的维度(例如"Petal.Length")放入代码输出的最后一行$mylot=renderPlot({myplotfunct(.

这个很管用。绘图呈现了我预期的效果。

然后,我添加了一个调试行来跟踪传递给该Plot函数的字符串的值。对啰。它是空的。为什么为空??似乎应该从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)})

})

推荐答案

最后两行中对DataetInput1和DatasetInput2的调用是导致错误的原因。

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

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

# Plot
output$myplot = renderPlot({myplotfunct(iris, datasetInput1(), datasetInput2())})
()允许您获取反应元素的值,而不是与反应元素本身交互。这是SHILINY的一个非常基本的概念,如果您还不熟悉这一点,也许可以重新访问shiny tutotial

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

这篇关于无法将类型&#39;闭包&#39;强制为类型&#39;字符&#39;的向量。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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