我有一些算法的命名列表,可能看起来像这样
> algorithm
$rBinarize
$rBinarize$x
[1] 40
并且可能包含任意数量的附加算法。每种算法都对空间对象(spObj
栅格类)执行操作并返回修改后的栅格。然后,我想do.call
在父函数中将这个(和所有其他)算法应用于原始输入。然而,我另外想要实现的是定义算法的顺序应用,即在前一个算法的输出上。我想出了以下代码,但我对提高性能的其他建议感到好奇,因为这是可能的。
if(sequential){
for(k in seq_along(algorithm)){
if(length(algorithm[[k]])==0){
args <- c(spObj = spObj)
} else{
args <- c(algorithm[[k]], spObj = spObj)
}
spObj <- do.call(what = names(algorithm)[k], args = args)
}
} else{
algorithm2 <- lapply(algorithm, function(x) x <- c(x, spObj = spObj))
modified <- sapply(seq_along(algorithm2), function(j) do.call(what = names(algorithm2)[[j]], args = algorithm2[[j]]))
}
难道不能使用某种apply()
构造来代替for
-loop吗?我不确定我是否只是不充分理解apply
/的逻辑,do.call
或者这在 R 中实际上是不可能的。
我修改为 for-loop 以使其与 Davids 的建议相媲美,并对其进行了微基准测试:
microbenchmark(a = for(k in seq_along(alg)){
if(length(alg[[k]][-1])==0){
args <- c(spObj = spObj)
} else{
args <- c(alg[[k]][-1], spObj = spObj)
}
spObj <- do.call(what = alg[[k]]$algorithm, args = args)
},
b = Reduce(f = function(x, y) do.call(what = y$algorithm, args = c(list(x), y[-1])),
x = alg,
init = spObj))
这导致
Unit: milliseconds
expr min lq mean median uq max neval
a 33.36777 35.22067 39.60699 36.79661 40.75072 152.0171 100
b 33.35236 35.39173 40.32860 37.51993 40.25102 154.0441 100
这是 for 循环实际上并不比任何其他解决方案慢的示例之一吗?