【问题标题】:How do I make a Shiny app read continuously from a file?如何让 Shiny 应用程序从文件中连续读取?
【发布时间】:2019-04-26 13:59:53
【问题描述】:

我正在编写一个相对简单的 Shiny 应用程序,它基本上需要读取一个文件,执行一些计算以创建一个新变量并输出该变量最近 5 个点的平均值。一个非常简化的应用版本:

require(shiny)

x1 <- 42
df.data <- read.csv("data.csv")
df.data$y2 <- df.data$y1/x1

ui <- fluidPage(
      h5(textOutput("calc1"))
)

server <- function(input, output, session) {

    output$calc1 <- renderText({
                    az <- nrow(df.data)
                    aa <- az - 5
                    y5m <- mean(df.data$y2[aa:az], na.rm=TRUE)
                    })
}

shinyApp(ui=ui, server=server)

文件由外部程序每分钟更新一次。我正在努力的部分是如何让应用程序读取文件(例如每 2 分钟)并保持最近 5 分钟的平均值更新。

我已经阅读过关于响应性的文章,但在读取文件时我似乎无法使其工作。我是 Shiny 的新手,所以也许我错过了一些基本概念。 有什么建议吗?

reactiveFileReader 是我一直在尝试使用的功能,但无法使其工作。我错过了什么?

server <- function(input, output, session) {
          df.data <- reactiveFileReader(1000, NULL, "data.csv", header=F)
          output$calc1 <- renderText({ ... })
}

【问题讨论】:

  • 看看reactiveFileReader()函数。
  • 你试过session而不是NULL吗?
  • 是的,但它不起作用。我收到类似reactive({rv$cookie valueFunc()}) 的消息,然后什么也没发生。

标签: r shiny


【解决方案1】:

通过使用invalidateLater() 函数我们可以做到这一点。

require(shiny)
ui <- fluidPage(
  h5(textOutput("calc1"))
)

server <- function(input, output, session) {
  df <- reactive({
    invalidateLater(120000, session) # equivalent milliseconds for 2 minutes
    x1 <- 42
    df.data <- read.csv("data.csv")
    df.data$y2 <- df.data$y1/x1
    return(df.data)
    })
  output$calc1 <- renderText({
    az <- nrow(df())
    aa <- az - 5
    y5m <- mean(df()$y2[aa:az], na.rm = TRUE)
  })
}

shinyApp(ui=ui, server=server)

【讨论】:

  • 道歉。错过了将列名从我的跟踪数据框中更改为根据您的代码。如果您遇到任何错误,请指出。
  • 这似乎效果更好,但我不明白y5m &lt;- mean(df()$Requirement[aa:az], na.rm = TRUE)。不应该是df()$y2吗? (我已删除此评论,现在重新发布)。使用df()$y2 它可以工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2016-10-30
相关资源
最近更新 更多