我有一个 test_vector
数字,我想标记向量中任何数字在另一个元素 20 以内的位置。知道如何在下面的示例中标记。
14550(位置 1)和 14554(位置 6)?
test_vector <- c(14550, 16072, 15099, 19434, 21040, 14554)
最佳答案
这是一个使用 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
关于r - 检测距离另一个元素一定距离内的数值向量元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33261785/