不能强制类型'封闭'类型为'字符'类型的矢量

Jer*_*ore 12 r shiny

我正在尝试使用闪亮的方法构建一个交互式散点图.使用虹膜数据,我希望用户选择散点图*花瓣与萼片的x和y尺寸,然后输出所选尺寸的简单散点图.非常直截了当.

首先,我需要构建一个允许我将表示维度的字符串传递给ggplot的函数.我做了这个并用静态数据测试了它.工作良好.

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

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

这似乎是出问题的地方.

我得到的错误是:错误:无法强制类型'封闭'类型为'字符'类型的向量

我已经采取了一些步骤来调试我的代码.我首先将硬编码维度(例如"Petal.Length")插入到我的代码输出的最后一行$ 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")
   )
  )
))
Run Code Online (Sandbox Code Playgroud)

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

})
Run Code Online (Sandbox Code Playgroud)

fai*_*ard 10

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

您应该调用datasetInput1()和datasetInput2().否则R尝试将函数转换为char.

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

在此输入图像描述

  • 这个答案解决了这个特定的问题,但没有告诉我根本原因是什么。 (3认同)
  • 请再读一遍:如果不输入(),则“ R尝试将函数转换为char” (2认同)