rvectorization

R: Keep function vectorized using all()


I have a function fun checking multiple conditions a, b. If all conditions are fulfilled, the function should return TRUE, else it should return FALSE.

a = 1
b = 0

fun <- function(a, b){
  all(a < 1,
      b < 1,
      na.rm = TRUE)
}

fun(a, b)

This function does the trick. However, if I use vectors now, all() does of course not keep the vector form but rather returns a single TRUE or FALSE.

I would like to have a function that works the same as the following one:

a = 1:2
b = 0:1

funV <- function(a, b){
  a < 1 & b < 1
}

funV(a, b)

but without chaining & and it should also work with missing values.


Solution

  • We can use Vectorize() for this to create a vectorized function. Vectorize() uses mapply() under the hood.

    fun <- function(a,b){
      all(a < 1,
          b < 1,
          na.rm = TRUE)
    }
    
    a = 1:2
    b = 0:1
    
    funV <- Vectorize(fun)
    
    funV(a,b)
    #> [1] FALSE FALSE
    

    Created on 2023-02-14 by the reprex package (v2.0.1)