这是一个想法,我们创建一个日志,所有使用的操作:=
都将存储在那里:
`:=` <- function(e1,e2){
log <- data.frame(
var = paste(collapse="\n",deparse(substitute(e1))),
call= paste(collapse="\n",deparse(substitute(e2))),
time = Sys.time()
)
if(exists(".log",envir = .GlobalEnv)){
assign(".log",
rbind(get(".log", envir = .GlobalEnv), log),
envir = .GlobalEnv)
} else {
assign(".log", log, envir = .GlobalEnv)
}
eval.parent(do.call(
substitute, list(match.call(), list(`:=` = quote(.Primitive("<-"))))))
}
x := 1
x := x+2
x
# [1] 3
.log
# var call time
# 1 x 1 2019-02-26 12:17:24
# 2 x x + 2 2019-02-26 12:17:25
通过一些调整,我们还可以记录<-
在全局环境中所做的每个分配,但它会减慢 R。
`<-` <- function(e1,e2){
if(identical(parent.frame(), .GlobalEnv)){
log <- data.frame(
var = paste(collapse="\n",deparse(substitute(e1))),
call= paste(collapse="\n",deparse(substitute(e2))),
time = Sys.time()
)
if(exists(".log",envir = .GlobalEnv)){
assign(".log",
rbind(get(".log", envir = .GlobalEnv), log),
envir = .GlobalEnv)
} else {
assign(".log", log, envir = .GlobalEnv)
}
}
eval.parent(do.call(substitute, list(
match.call(), list(`<-` = quote(.Primitive("<-"))))))
}
rm(.log)
var <- 1
var <- var +1
var
fun <- function(x) {y <- x+1; y}
var2 <- fun(var)
var
# [1] 2
var2
# [1] 3
.log
# var call time
# 1 var 1 2019-02-26 12:52:13
# 2 var var + 1 2019-02-26 12:52:13
# 3 fun function(x) {\n y <- x + 1\n y\n} 2019-02-26 12:52:14
# 4 var2 fun(var) 2019-02-26 12:52:14