【问题标题】:Check lengths of elements in list of equal length检查等长列表中元素的长度
【发布时间】:2015-12-29 13:03:53
【问题描述】:

检查列表中的元素是否等长?

例如:

l <- list(c(1:3),c(2:7),c(12:13))

[[1]]
[1] 1 2 3

[[2]]
[1] 2 3 4 5 6 7

[[3]]
[1] 12 13

我有一个包含许多条目的长列表,并且想要一种方法来检查每个元素是否具有相同的长度。

由于长度不同 (3,6,2),它应该返回 FALSE。

【问题讨论】:

    标签: r list


    【解决方案1】:

    试试这个:

    length(unique(sapply(l, length))) == 1
    # [1] FALSE
    

    或者@PierreLafortune 的方式:

    length(unique(lengths(l))) == 1L
    

    或者@CathG 的方式:

    all(sapply(l, length) == length(l[[1]])) 
    #or
    all(lengths(l) == length(l[[1]]))
    

    一些基准测试:

    #data
    set.seed(123)
    l <- lapply(round(runif(1000,1,100)), runif)
    
    
    library(microbenchmark)
    library(ggplot2)
    
    #benchmark
    bm <-   microbenchmark(
      zx8754 = length(unique(sapply(l, length))) == 1,
      PierreLafortune=length(unique(lengths(l))) == 1L,
      CathG_1 = all(lengths(l) == length(l[[1]])),
      CathG_2 = all(sapply(l, length) == length(l[[1]])),
      times = 10000)
    
    # result
    bm
    Unit: microseconds
                expr     min      lq      mean  median      uq       max neval  cld
              zx8754 326.605 355.281 392.39741 364.034 377.618 84109.597 10000    d
     PierreLafortune  23.545  25.960  30.24049  27.168  28.375  3312.829 10000  b  
             CathG_1   9.056  11.471  13.49464  12.679  13.584  1832.847 10000 a   
             CathG_2 319.965 343.207 371.50327 351.659 364.940  3531.068 10000   c 
    
    #plot benchmark
    autoplot(bm)
    

    【讨论】:

    • @CathG that won't work as length(l) 将检查列表中存储桶的数量(即 3)。
    • @Nick 对,对不起,错字,我的意思是lengths 是第一个(就像在另一个答案中一样)
    【解决方案2】:

    我会使用:

    length(unique(lengths(l))) == 1L
    [1] FALSE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多