Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vectorize modulo?

In R, I have a vector with integers which shall be checked to be divisible without remainder for multiple values.

v <- c(3, 4, 10, 11, 12)
v %% 4 == 0 | v %% 10 == 0 #... this might include 100 checks or more

I'm looking for a vectorization of this (like v %% c(4, 10)) which might return a matrix or something similar.


I programmed a function that can do it, but I wonder if there exists already such a function I can reuse instead of "reinventing" it again.

`%V%`  <- function(x, y){
  ret <- matrix(nrow = length(x), ncol = length(y))
  for(i in 1:ncol(ret)){
    ret[, i] <- x %% y[i]
  }
  return(ret)
}
v %V% c(4, 10)

For my initial purpose I would now run apply(v %V% c(4, 10), 1, function(x) any(x == 0)) or change my function accordingly.

like image 861
Qaswed Avatar asked Jul 16 '26 16:07

Qaswed


1 Answers

You can use the outer-function to achieve what you want:

outer(v, c(4,10), '%%') == 0

which gives:

      [,1]  [,2]
[1,] FALSE FALSE
[2,]  TRUE FALSE
[3,] FALSE  TRUE
[4,] FALSE FALSE
[5,]  TRUE FALSE
like image 165
Jaap Avatar answered Jul 19 '26 08:07

Jaap