Can I assign an operator to a variable?
In R, is it possible to assign an operator to a variable or some other construct that allows开发者_如何学Python the variable to be used as an operator? In my case, I want some code to use either the %do% or %dopar% operator from the foreach package (depending on whether the user wants parallel computation or not). The block of code to execute remains the same, its just the operator that's variable.
This is called operator overloading, and here is a simple example:
"%do%" <- function(a, b){
if(do_plus){
a + b
} else {
a - b
}
}
do_plus <- TRUE
3 %do% 4
[1] 7
do_plus <- FALSE
3 %do% 4
[1] -1
You're asking the wrong question. Just use %dopar%
and call registerDoSEQ
if you're not running in parallel. With %dopar%
, the code doesn't change, just the backend does.
精彩评论