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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With