2016-06-17 12 views
6

Ich habe erster Vektor, Beispiel: x=1:10 und zweite mit Primzahlen Beispiel y=c(2,3,5,7)die Division zwei Vektoren

Und ich will Art Vektor x: durch 2 teilbar, durch 3 teilbar, usw. Also, der Ausgang wie folgt aussehen würde: 2 4 6 8 10 3 9 5 7

Antwort

6

mit apply Schleife und mod:

unique(unlist(sapply(y, function(i)x[x%%i == 0]))) 
# [1] 2 4 6 8 10 3 9 5 7 

Oder mit as.logical statt ==, von @ZheyuanLi vorgeschlagen:

unique(unlist(sapply(y, function(i) x[!as.logical(x%%i)]))) 

ähnlichem Ansatz expand.grid statt gilt:

xy <- expand.grid(x, y) 
unique(xy[ xy[,1]%%xy[,2] == 0, 1]) 
0

Eine weitere Option ist

unique(rep(x, length(y))[rep(x, length(y))%% rep(y, each = length(x))==0]) 
#[1] 2 4 6 8 10 3 9 5 7