简体   繁体   English

寻找更高效的ifelse()

[英]Looking for a more efficient ifelse()

While R's ifelse is incredibly handy, it does have a particular shortcoming: in the call ifelse(test, yes, no) all elements of yes and no are evaluated, even those that will be thrown away. 虽然R的ifelse非常方便,但它确实有一个特别的缺点:在调用ifelse(test, yes, no)所有的yesno元素都会被评估,甚至是那些将被丢弃的元素。

This is rather wasteful if you're using it in the middle of a complicated numerical exercise, say in a function that will be fed to integrate , uniroot , optim or whatever. 如果你在一个复杂的数字练习中使用它,比如在一个函数中,它将被用于integrateunirootoptim或其他任何东西,这是相当浪费的。 For example, one might have 例如,有人可能有

ifelse(test, f(x, y, z), g(a, b, c))

where f and g are arbitrarily complex or slow functions, possibly involving more nested ifelse 's. 其中fg是任意复杂或慢的函数,可能涉及更多嵌套的ifelse

Has anyone written a replacement for ifelse that only evaluates the elements of yes / no that will be kept? 是否有人写过ifelse的替代ifelse ,只评估将保留的yes / no的元素? Basically, something along the lines of 基本上,有些东西沿袭

out <- test
for(i in seq_along(out))
{
    if(test[i]) out[i] <- f(x[i], y[i], z[i])
    else out[i] <- g(a[i], b[i], c[i])
}

but without the clumsiness/inefficiency of an explicit loop. 但没有显式循环的笨拙/低效。 Is this even possible without getting into the innards of R? 如果没有进入R的内部,这是否可能?

I don't think that the problem is ifelse . 我不认为问题是ifelse f and g are only being evaluated once in your expression. fg仅在表达式中被评估一次。 I think your problem is that f and g are slow with vectors. 我认为你的问题是fg在向量方面很慢。

You could change the calls to f and g so that they only get evaluated on a subset of the vector. 您可以将调用更改为fg以便仅在向量的子集上进行求值。

out <- numeric(length(test))  #or whatever the output type is
out[test] <- f(x[test], y[test], z[test])
out[!test] <- g(x[!test], y[!test], z[!test])

You'll need to adjust this if any elements of test are NA . 如果test任何元素是NA则需要调整此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM