除二向量
Division two vectors
我有第一个向量,例如:x=1:10
,第二个是素数,例如y=c(2,3,5,7)
我想要 sort 向量 x:可被 2 整除,可被 3 整除,等等。
因此,输出将如下所示:2 4 6 8 10 3 9 5 7
使用 apply
循环和 mod
:
unique(unlist(sapply(y, function(i)x[x%%i == 0])))
# [1] 2 4 6 8 10 3 9 5 7
或使用as.logical
代替==
,由@ZheyuanLi建议:
unique(unlist(sapply(y, function(i) x[!as.logical(x%%i)])))
使用 expand.grid 而不是应用的类似方法:
xy <- expand.grid(x, y)
unique(xy[ xy[,1]%%xy[,2] == 0, 1])
另一种选择是
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
我有第一个向量,例如:x=1:10
,第二个是素数,例如y=c(2,3,5,7)
我想要 sort 向量 x:可被 2 整除,可被 3 整除,等等。
因此,输出将如下所示:2 4 6 8 10 3 9 5 7
使用 apply
循环和 mod
:
unique(unlist(sapply(y, function(i)x[x%%i == 0])))
# [1] 2 4 6 8 10 3 9 5 7
或使用as.logical
代替==
,由@ZheyuanLi建议:
unique(unlist(sapply(y, function(i) x[!as.logical(x%%i)])))
使用 expand.grid 而不是应用的类似方法:
xy <- expand.grid(x, y)
unique(xy[ xy[,1]%%xy[,2] == 0, 1])
另一种选择是
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