我有这个整数向量:
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 the index然后添加-10:10的数字序列来获取unique
元素和sort
,而不是循环。
out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
identical(out, out2)
#[1] TRUE
就个人而言,我会使用outer
而不是map
:
sort(unique(outer(index, -10:10, "+")))
并且,正如akrun所示,如果您不想嵌套东西,可以使用管道。