我想制作一个基本的分析工具,它可以收集时间戳并用注释产生运行时间。唯一的问题是我无法在不使用全局变量的情况下弄清楚如何做到这一点。实现我想要实现的功能的“正确”方法是什么?如果R已经内置了这个功能,那真是太棒了,但我真正想弄清楚的是如何避免使用全局变量并编写更强大的代码。
timeStamps = c()
runTimes = list()
appendRunTimes <- function(note) {
if(length(timeStamps) < 1) {
timeStamps <<- Sys.time()
}
else {
timeStamps <<- c(timeStamps, Sys.time())
diff <- timeStamps[length(timeStamps) ] - timeStamps[length(timeStamps) - 1]
runTimes <<- c(runTimes, format(diff))
names(runTimes)[length(runTimes)] <<- note
}
}
appendRunTimes('start')
Sys.sleep(4)
appendRunTimes('test')
答案 0 :(得分:7)
以下是使用闭包重写的示例:
RTmonitor <- local({
timeStamps = c()
runTimes = list()
list(
appendRunTimes=function(note) {
if(length(timeStamps) < 1) {
timeStamps <<- Sys.time()
}
else {
timeStamps <<- c(timeStamps, Sys.time())
diff <- timeStamps[length(timeStamps) ] - timeStamps[length(timeStamps) - 1]
runTimes <<- c(runTimes, format(diff))
names(runTimes)[length(runTimes)] <<- note
}
},
viewRunTimes=function() {
return(list(timeStamps=timeStamps,runTimes=runTimes))
})
})
> RTmonitor$appendRunTimes("start")
> RTmonitor$appendRunTimes("test")
> RTmonitor$viewRunTimes()
$timeStamps
[1] "2013-01-04 18:39:12 EST" "2013-01-04 18:39:21 EST"
$runTimes
$runTimes$test
[1] "8.855587 secs"
观察到值存储在闭包内,而不是存储在全局环境中:
> timeStamps
Error: object 'timeStamps' not found
> runTimes
Error: object 'runTimes' not found
> RTmonitor$timeStamps
NULL
> RTmonitor$runTimes
NULL
关于闭包和避免全局变量的更多阅读:
答案 1 :(得分:4)
现在使用ReferenceClasses执行此操作:
RTmonitor = setRefClass("RTmonitor",
fields=list(
timeStamps="POSIXct",
runTimes = "list"
),
methods=list(
appendRunTimes=function(note){
if(length(timeStamps)==0){
timeStamps <<- Sys.time()
}else{
timeStamps <<- c(timeStamps, Sys.time())
diff <- timeStamps[length(timeStamps) ] - timeStamps[length(timeStamps) - 1]
runTimes <<- c(runTimes, format(diff))
names(runTimes)[length(runTimes)] <<- note
}
}
)
)
现在你已经定义了一个类,实例化了一个对象并使用它:
> r = RTmonitor$new()
> r$appendRunTimes("start")
> r$appendRunTimes("test")
> r
Reference class object of class "RTmonitor"
Field "timeStamps":
[1] "2013-01-05 14:52:25 GMT" "2013-01-05 14:52:31 GMT"
Field "runTimes":
$test
[1] "5.175815 secs"
非常类似于闭包方法,但更正式化。例如,我必须将timeStamps
字段定义为POSIXct
。你也可以用这种方式创建多个RTmonitor
对象,它们可以独立工作 - 你必须编写一个封装构造函数来封装闭包来做到这一点。