【发布时间】:2018-01-17 18:54:54
【问题描述】:
我不熟悉将 Shiny 与 R 结合使用。我必须开发一个 Web 应用程序来显示基于年份范围的图表。 Shiny 服务器必须从 ui(开始年份和结束年份)获取输入并进行计算并绘制输出。我编写了 R 脚本来制作一个名为 years 的向量,其中包含所选范围内的不同年份,并将其绑定到数据框。然后,随后将新的计算列添加到表中并绘制不同的列。 这是代码
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "startyear",
label = "Choose starting year",
value = 25, min = 2016, max = 2050),
sliderInput(inputId = "endyear",
label = "Choose ending year",
value = 25, min = 2016, max = 2050),
plotOutput("plot1"),
plotOutput("plot2"),
plotOutput("plot3")
)
server <- function(input, output) {
years <- reactive({(input$startyear:input$endyear)})
sample <- data.frame(years)
sample$timestepdays <- (sample$years-min(sample$years))*365
sample$timestep <- (sample$years-min(sample$years))
sample$pop <- sample$timestepdays *500 +839000
sample$no_of_trips <- sample$pop*4.4045
sample$NE <- sample$no_of_trips*0.00000003+0.3738
sample$Delta_VE_logit <- sample$timestep*(-0.149) +5
sample$Delta_VE <- (exp(sample$Delta_VE_logit)/(exp(sample$Delta_VE_logit)+1))*(1-0.5)+0.5
sample$VMT <- 7.3 * sample$no_of_trips
sample$ER_per_mile <- sample$Delta_VE * sample$NE
sample$CO2 <- (sample$ER_per_mile * sample$VMT ) /10000
output$plot1 <- renderPlot({lines.default(sample&years,sample$population)})
output$plot2 <- renderPlot({lines.default(sample&years,sample$no_of_trips)})
output$plot3 <- renderPlot({lines.default(sample&no_of_trips,sample$NE)})
}
shinyApp(ui = ui, server = server)
我收到以下错误
Warning: Error in as.data.frame.default: cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame
Stack trace (innermost first):
40: as.data.frame.default
39: as.data.frame
38: data.frame
37: server [C:/Users/R-Jaikumar/Downloads/shiny-quickstart-1/downloads/code/01-template.R#17]
1: runApp
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "c("reactiveExpr", "reactive")" to a data.frame
【问题讨论】:
-
一旦你创建了一个变量
reactive({}),从那时起你需要将它称为variable()。所以sample <- data.frame(years)应该是sample <- data.frame(years())。 -
嘿,谢谢,我在修改更改后收到以下错误。 .getReactiveEnvironment()$currentContext 中的错误:如果没有活动的反应上下文,则不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。
-
我猜大概是
sample,应该是响应式而不是data.frame