我有一个- clone the online repo under your user namespace (github online features)
- clone your copy locally on your machine (`git clone ...`)
- checkout to the target branch (`git checkout ...`)
- create the new branch (`git checkout -b your_branch_name`)
个数字,我想在另一个元素的20之内标记任意数字的向量中的位置。知道如何在下面的例子中标记。
14550(位置1)和14554(位置6)?
test_vector
答案 0 :(得分:5)
以下是使用outer
x[rowSums(abs(outer(x, x, `-`)) < 20) > 1]
## [1] 14550 14554
或者如果想要位置
which(rowSums(abs(outer(x, x, `-`)) < 20) > 1)
## [1] 1 6
针对拟议替代方案的一些基准
set.seed(123)
x <- sample(1e6, 1e3)
microbenchmark(Outer = which(rowSums(abs(outer(x, x, `-`)) < 20) > 1),
Sapply = which(rowSums(abs(sapply(x, `-`, x)) < 20) > 1),
Vapply = which(rowSums(abs(vapply(x, `-`, x, FUN.VALUE = double(length(x)))) < 20) > 1),
Dist = which(rowSums(as.matrix(dist(x)) < 20) > 1))
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# Outer 16.43502 17.84158 30.22553 18.99517 58.39895 64.28932 100 a
# Sapply 24.66530 26.64898 39.44647 27.72899 67.83102 75.59510 100 b
# Vapply 15.05799 16.62862 25.52292 17.57840 18.94187 64.09142 100 a
# Dist 62.25154 66.00407 95.46239 104.26654 107.21883 150.30602 100 c
答案 1 :(得分:3)
与@RHertel讨论后:
w = which(dist(x) < 20)
pairs = t(combn(length(x),2))
pairs[w, , drop = FALSE]
# [,1] [,2]
# [1,] 1 6
这样,您可以看到哪些元素对彼此相差20个单位。如果您只想要元素索引列表,那就是unique(c(pairs[w,]))
。