从整数向量中,构建一个较长的向量,包括与原始距离最多为10的所有整数

问题描述 投票:2回答:2

我有这个整数向量:

m <- 10
n <- 1000
index <- sample(seq_len(n), m)

我想扩展index,包括所有与index中一个值的距离不大于10的整数,并消除重复。使用nm的当前值不太可能重复,但是比抱歉更安全,并且无论如何解决方案必须使用nm的通用值,使用m<n

现在我做以下事情:

library(purrr)
index <- unique(sort(unlist(map(index, function(x) seq(x - 10, x + 10)))))

这有效,但它不是非常易读。有更好的想法吗?

r vector seq
2个回答
4
投票

我们可以管它以使其可读

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

我们也可以通过replicating the index然后添加-10:10的数字序列来获取unique元素和sort,而不是循环。

out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
identical(out, out2)
#[1] TRUE

3
投票

就个人而言,我会使用outer而不是map

sort(unique(outer(index, -10:10, "+")))

并且,正如akrun所示,如果您不想嵌套东西,可以使用管道。

© www.soinside.com 2019 - 2024. All rights reserved.