从整数向量构建一个更长的向量,包括与原始整数的距离最多为 10 的所有整数
From a vector of integers, build a longer vector including all integers whose distance from the original ones is at most 10
我有这个整数向量:
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
元素和 sort
out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
identical(out, out2)
#[1] TRUE
我个人会使用 outer
而不是 map
:
sort(unique(outer(index, -10:10, "+")))
而且,如 akrun 所示,如果您不想嵌套,可以使用管道。
我有这个整数向量:
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
元素和 sort
out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
identical(out, out2)
#[1] TRUE
我个人会使用 outer
而不是 map
:
sort(unique(outer(index, -10:10, "+")))
而且,如 akrun 所示,如果您不想嵌套,可以使用管道。