我试着用闪亮构建一个互动的散点图。使用虹膜数据,我想让用户选择散点图*花瓣与萼片的x和y维数,然后输出所选维度的简单散点图。相当直截了当。
首先,我需要构建一个函数,该函数允许我将表示维度的字符串传递给ggplot。我做了这个,用静态数据测试了它。效果很好。
接下来,我为花瓣和萼片定义了两个下拉和两个后续字符串(使用闪亮的)(这是我的x和y轴)。
接下来,我使用switch的反应性()函数使用switch语句设置两个字符串变量。
这似乎是事情出错的地方。
我得到的错误是:错误:不能强迫类型‘闭包’到‘字符’类型的向量
我已经采取了许多步骤来调试我的代码。我首先插入了硬编码的维度。( "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")
)
)
))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)})
})发布于 2015-04-23 09:49:00
最后两行中对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())})()允许您获取反应性元素的值,而不是与反应性元素本身交互。这是一个非常基本的概念,有光泽,如果这还不是你所熟悉的东西,也许可以重新审视一下闪亮教程。
只要添加(),错误就会消失,如下所示:

https://stackoverflow.com/questions/29812633
复制相似问题