我正在运行一个模拟,我需要跟踪特定条件的函数调用中的出现次数。我试图通过分配给全局对象来完成此操作。如果您运行该功能,它会起作用,但如果您尝试 lapply
就像我在做的那样,你会得到一个条件发生的所有次数的计数,而不是对 list
中的每个元素发生的每次发生的计数。送至 lapply
.
这是一个虚拟情况,其中出现的是数字的偶数:
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
它在模拟中,所以速度是一个问题。我希望这尽可能快,所以我不会嫁给全局分配的想法。
最佳答案
与其分配给全局环境,不如直接分配给内部 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
关于r - 计算 lapply 中条件的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848984/