我正在运行一个模拟,我需要跟踪特定条件的函数调用中出现的次数。我试图通过向全局对象赋值来实现这一点。如果你运行这个函数,它是有效的,但是如果你像我这样尝试lapply
这个函数,你会得到一个关于所有条件发生次数的计数,而不是每次输入到lapply
的list
中每个元素发生的次数的计数。
这里是一个虚拟的情况,其中出现的是一个数字的均衡性:
FUN <- function(x){
lapply(1:length(x), function(i) {
y <- x[i]
if (y %% 2 == 0){
assign("count.occurrences", count.occurrences + 1, env=.GlobalEnv)
}
print("do something")
})
list(guy="x", count=count.occurrences)
}
#works as expected
count.occurrences <- 0
FUN(1:10)
count.occurrences <- 0
lapply(list(1:10, 1:3, 11:16, 9), FUN)
#gives me...
#> count.occurrences
#[1] 9
#I want...
#> count.occurrences
#[1] 5 1 3 0
这是在模拟中,所以速度是一个问题。我希望这件事越快越好,这样我就不会被全局赋值的想法困扰。
发布于 2012-08-07 16:36:46
与其分配给全局环境,为什么不直接分配给FUN
的内部环境呢?
FUN <- function(x){
count.occurances <- 0
lapply(1:length(x), function(i) {
y <- x[i]
if (y %% 2 == 0){
count.occurances <<- count.occurances + 1
}
print("do something")
})
list(guy="x", count=count.occurances)
}
Z <- lapply(list(1:10, 1:3, 11:16, 9), FUN)
然后你就可以把计数拉出来了。
> sapply(Z, `[[`, "count")
[1] 5 1 3 0
发布于 2012-08-07 16:24:25
我还没有对此做过任何基准测试,但是您是否尝试过仅使用for
循环?我知道循环在R中通常不被鼓励,但它们也不总是很慢。
FUN <- function(x) {
count.occurrences = 0
for (i in 1:length(x)) {
y = x[i]
if (y %% 2 == 0) {
count.occurrences = count.occurrences + 1
}
print("do something")
}
list(guy="x", count=count.occurrences)
}
lapply(list(1:10, 1:3, 11:16, 9), FUN)
发布于 2012-08-07 16:23:35
我可以像这样得到它:
count.occurances <- 0
Z <-lapply(list(1:10, 1:3, 11:16, 9), FUN)
diff(c(0, sapply(1:length(Z), function(x) Z[[x]]$count)))
我对更好的想法(更快)持开放态度。
https://stackoverflow.com/questions/11848984
复制相似问题