R中微基准标记后的奇怪印刷行为

时间:2016-06-15 14:06:36

标签: r scoping microbenchmark

我正在关注@ m0h3n关于this几天前提出的问题的帖子,我注意到R在运行microbenchmark()后表现得很奇怪。这是代码:

library(data.table)
library(microbenchmark)

data<- data.table(id=c("p1","p1","p1","p2","p2"),date=c("d1","d1","d1","d2","d2"))
p<-5 #just to test after benchmark

func_Bryan.Goggin <- function(x){x[, `:=` (date = ifelse(duplicated(date), NA, date)), by = id];x}
func_Richard.Scriven1 <- function(x){x$date <- ave(x$date, x$id, FUN = function(a) replace(a, duplicated(a), NA_integer_));x;}
func_Richard.Scriven2 <- function(x){x[duplicated(date), date := date[NA], by = id];x;}
func_r2evans <- function(x){groupedx <- by(x, x$date, function(df) {within(df, date <- c(as.character(date[1]), rep(NA, nrow(df) - 1)))});Reduce(rbind, groupedx);groupedx;}
microbenchmark(func_Bryan.Goggin(data), func_Richard.Scriven1(data), func_Richard.Scriven2(data), func_r2evans(data))
#note I changed these functions from the original post a little to see how speed was affected.

p # [1] 5

data # nothing, wont print
data # works

运行基准测试后,调用data不返回任何内容。我添加了p<-5以查看它是否知道它是什么,并且它工作正常,但在运行基准后请求data不返回任何内容。它将在第二次询问时定期打印。

这不是一个非常大的问题,但我想知道是否有人知道导致这种情况发生的原因。运行microbenchmark()后我直接尝试了print(data)return(data)(如果它被包含在其中一个函数中),它仍然不会第一次打印。我猜它是某种范围问题,但我不是该领域的专家。我还检查了environment(),它返回<environment: R_GlobalEnv>

0 个答案:

没有答案