代码之家  ›  专栏  ›  技术社区  ›  DeltaIV

从一个整数向量,建立一个较长的向量,包括所有整数的距离,从原来的一个最多是10

  •  2
  • DeltaIV  · 技术社区  · 7 年前

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

    我想延长 index 指数 不大于10,并消除重复项。重复的可能性不大,当前值为 n m 无论如何,该解决方案必须使用 n m<n .

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

    这是可行的,但它不完全可读。有更好的主意吗?

    2 回复  |  直到 7 年前
        1
  •  4
  •   akrun    7 年前

    我们可以通过管道把它读出来

    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 对索引进行运算,然后将-10:10的数字序列相加,得到 unique 元素和 sort

    out2 <- sort(unique(rep(index, each = 21) + (-10:10)))
    identical(out, out2)
    #[1] TRUE
    
        2
  •  3
  •   Gregor Thomas    7 年前

    outer 而不是 map

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

    而且,如akrun所示,如果您不喜欢嵌套东西,可以使用管道。

    推荐文章