Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 591
DuesserBaest Avatar asked May 22 '26 22:05

DuesserBaest


2 Answers

pmin + as.logical = vectorized all().

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

fun(1:2, 0:1)
# [1] FALSE FALSE

Benchmark

# Unit: milliseconds
#              expr        min         lq       mean     median         uq        max neval
#    pmin_all(a, b)   1.816587   1.843934   2.223257   1.868905   3.004286   5.936595   100
#  mapply_all(a, b) 181.204836 183.868243 188.579629 185.331190 188.332364 347.997674   100
#     vec_all(a, b) 186.911905 190.187575 194.159146 192.135094 194.848294 218.416740   100
pmin_all <- function(a, b){
  as.logical(pmin(a < 1, b < 1, na.rm = TRUE))
}

mapply_all <- function(a, b){
  mapply(\(x, y) all(x < 1, y < 1, na.rm = TRUE), a, b)
}

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

a <- rnorm(1e5, mean = 1)
b <- rnorm(1e5, mean = 1)

library(microbenchmark)

bm <- microbenchmark(
  pmin_all(a, b),
  mapply_all(a, b),
  vec_all(a, b),
  check = 'identical'
)
like image 59
Darren Tsai Avatar answered May 24 '26 15:05

Darren Tsai


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)

like image 32
TimTeaFan Avatar answered May 24 '26 17:05

TimTeaFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!