分两个向量

Rob*_*ert 6 r vector division

我有第一个矢量,例子:x=1:10和第二个素数,例子y=c(2,3,5,7)

我想要排序向量x:可被2整除,可被3整除等等.所以,输出看起来像这样:2 4 6 8 10 3 9 5 7

zx8*_*754 6

使用apply循环和mod:

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

或者使用as.logical的,而不是==由@ZheyuanLi建议:

unique(unlist(sapply(y, function(i) x[!as.logical(x%%i)])))
Run Code Online (Sandbox Code Playgroud)

使用expand.grid而不是apply的类似方法:

xy <- expand.grid(x, y)
unique(xy[ xy[,1]%%xy[,2] == 0, 1])
Run Code Online (Sandbox Code Playgroud)