I have first vector, example: x=1:10
and second with prime numbers, example y=c(2,3,5,7)
And I want sort vector x: divisible by 2, divisible by 3, etc.
So, The output would look like this: 2 4 6 8 10 3 9 5 7
Using apply
loop and mod
:
unique(unlist(sapply(y, function(i)x[x%%i == 0])))
# [1] 2 4 6 8 10 3 9 5 7
Or using as.logical
instead of ==
, suggested by @ZheyuanLi:
unique(unlist(sapply(y, function(i) x[!as.logical(x%%i)])))
Similar approach using expand.grid instead of apply:
xy <- expand.grid(x, y)
unique(xy[ xy[,1]%%xy[,2] == 0, 1])
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