你可以用闭包来做到这一点。闭包允许函数在调用之间保持其状态。
每次timer() 运行时,它都会创建一个新环境并初始化该环境中的时间。然后它创建一个新函数来维护对其创建环境的访问。然后使用<<-操作符将x变量上一层修改,就可以存储每次函数调用的时间。
library(shiny)
timer <- function(){
x <- Sys.time()
y <- function(){
y <- x
x <<- Sys.time()
return(x-y)
}
return(y)
}
# Implement a simple shiny app with an action button that
# prints the result of running click()
ui <- fluidPage(
actionButton("do", "Click Me")
)
server <- function(input, output, session) {
# click is defined within the server function so each
# session has their own click function with a stored
# time.
click <- timer()
observeEvent(input$do, {print(click())})
}
shinyApp(ui, server)
有关此技术的更多信息,您可以阅读 Hadley Wickham 的 Advanced R: Functional Programming
编辑:如果您想忽略第一次点击/在第一次点击时返回其他内容,您可以执行以下操作:
library(shiny)
timer <- function(){
x <- NULL
y <- function(){
y <- x
x <<- Sys.time()
if(is.null(y))
return("first click")
return(x-y)
}
return(y)
}
# Implement a simple shiny app with an action button that
# prints the result of running click()
ui <- fluidPage(
actionButton("do", "Click Me")
)
server <- function(input, output, session) {
# click is defined within the server function so each
# session has their own click function with a stored
# time.
click <- timer()
observeEvent(input$do, {print(click())})
}
shinyApp(ui, server)