【发布时间】:2015-10-03 07:40:19
【问题描述】:
我有一个每分钟自动更新新数据的 .csv。我想让 R Shiny 每小时用这个新数据集重新更新一次。
据我所见,这将涉及invalidateLater 或autoInvalidate;但是,我不确定如何让这些工作(或更重要的是,将它们放在哪里)。
ui.R 非常简单,所以我不会包含它。 server.R 如下:
library(ggplot2)
library(reshape2)
library(scales)
# data <- reactive({ # data refresh once a day # 86400000ms is 1 day
# invalidateLater(10000, session) # 10s to test
# })
shinyServer(function(input, output, session) {
autoInvalidate <- reactiveTimer(10000, session)
observe({
x <- read.csv("wait_times.csv", header=T, stringsAsFactors=FALSE)
x <- rename(x, c("Fall.River" = "Fall River", "Martha.s.Vineyard" = "Martha's Vineyard", "New.Bedford" = "New Bedford", "North.Adams" = "North Adams", "South.Yarmouth" = "South Yarmouth"))
cities <- colnames(x)[-1]
x[x == 999] <- NA
x_long <- melt(x, id.var="timestamp") ### does not work after Attleboro ###
x_long <- rename(x_long, c("variable" = "city", "value" = "wait_time"))
x_long$timestamp <- strptime(x_long$timestamp, "%d/%m/%Y %H:%M %p")
weeks <- as.double(difftime(x_long$timestamp[1], x_long$timestamp[length(x_long$timestamp)], units = "weeks")) + 1
print("REFRESHING CSV!")
autoInvalidate()
})
# pass server-side code into initial UI page
output$cities <- renderUI({
checkboxGroupInput("cities",
label = h3("Which cities to view?"),
as.list(cities),
selected = "Boston")
})
output$weeks <- renderUI({
sliderInput("weeks",
label = h3("How many prior weeks to average?"),
min = 1,
max = weeks,
step = 1,
value = 1)
})
output$main <- renderPlot({
x_output <- x_long[x_long$city == input$cities, ]
p <- ggplot(x_output, aes(x=timestamp, y=wait_time, group=city)) + geom_line(aes(color=city), size=1.5) + scale_x_datetime(breaks = date_breaks("10 min")) + theme(axis.text.x = element_text(angle = 90, hjust=1), legend.position = "bottom") + labs(x=NULL, y="Waiting time (minutes)")
print(p)
})
})
当我从 .csv 中提取某些值(例如“周”和“城市”)时,R Shiny 说它们不存在:
Error in as.list(cities) : object 'cities' not found
Error in sliderInput("weeks", label = h3("How many prior weeks to average?"), :
object 'weeks' not found
Error in func() : object 'x_long' not found
我认为正在发生的事情是,由于这些是在 observe 函数中声明的,因此它们被它封装了。也许我应该更早地使这些无效/声明?我已经尝试在声明 shinyServer() 之前将它们放入,但这似乎也不起作用。
我研究了这些来源,但无法复制:
【问题讨论】:
标签: r refresh shiny auto-update