Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division two vectors

Tags:

r

vector

division

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

like image 962
Robert Avatar asked Jun 17 '16 21:06

Robert


1 Answers

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])
like image 176
zx8754 Avatar answered Sep 20 '22 05:09

zx8754