我有这个整数向量:
m <- 10
n <- 1000
index <- sample(seq_len(n), m)
我想延长index
, 通过包括所有与 index
中的值之一的距离的整数不大于10,剔除重复项。重复的可能性不大,当前值为 n
和 m
,但安全总比遗憾好,无论如何,解决方案必须使用 n
的通用值和 m
, 与 m<n
强>。
现在我做了以下事情:
library(purrr)
index <- unique(sort(unlist(map(index, function(x) seq(x - 10, x + 10)))))
这行得通,但可读性不是很好。有更好的想法吗?
最佳答案
我们可以通过管道传递它以使其可读
library(tidyverse)
out <- map(index, ~ seq(.x - 10, .x + 10) ) %>% # get the sequence
unlist %>% # unlist the list to a vector
unique %>% # get the unique values
sort # sort
除了循环之外,我们还可以通过rep
licating 索引来对其进行矢量化,然后添加从-10:10 开始的数字序列,获取unique
元素和排序
out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
identical(out, out2)
#[1] TRUE
关于r - 从整数向量构建一个更长的向量,包括与原始整数的距离最多为 10 的所有整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319414/