代码之家  ›  专栏  ›  技术社区  ›  Roman LuÅ¡trik

从列表中查找唯一值

  •  27
  • Roman LuÅ¡trik  · 技术社区  · 14 年前

    假设您有一个值列表

    x <- list(a=c(1,2,3), b = c(2,3,4), c=c(4,5,6))
    

    我想从所有组合的列表元素中找到唯一的值。到目前为止,下面的代码实现了这个技巧

    unique(unlist(x))
    

    有人知道更有效的方法吗?我有一个有很多价值观的清单,如果能加快速度我会很感激的。

    1 回复  |  直到 9 年前
        1
  •  41
  •   Gavin Simpson    14 年前

    > unique(unlist(x, use.names = FALSE))
    [1] 1 2 3 4 5 6
    

    unique() x

    > unique(unlist(x))
    [1] 1 2 3 4 5 6
    > unique.default(sapply(x, unique))
    [1] 1 2 3 4 5 6
    

    unique.default matrix unique

    unlist names use.names

    >

    ## Create a large list (1000 components of length 100 each)
    DF <- as.list(data.frame(matrix(sample(1:10, 1000*1000, replace = TRUE), 
                                    ncol = 1000)))
    

    DF

    > ## Do the three approaches give the same result:
    > all.equal(unique.default(sapply(DF, unique)), unique(unlist(DF)))
    [1] TRUE
    > all.equal(unique(unlist(DF, use.names = FALSE)), unique(unlist(DF)))
    [1] TRUE
    > ## Timing Roman's original:
    > system.time(replicate(10, unique(unlist(DF))))
       user  system elapsed 
      12.884   0.077  12.966
    > ## Timing double unique version:
    > system.time(replicate(10, unique.default(sapply(DF, unique))))
       user  system elapsed 
      0.648   0.000   0.653
    > ## timing of Marek's solution:
    > system.time(replicate(10, unique(unlist(DF, use.names = FALSE))))
       user  system elapsed 
      0.510   0.000   0.512
    

    sapply