代码之家  ›  专栏  ›  技术社区  ›  Michael Gruenstaeudl

R-通过值计数确定固定宽度的范围

  •  1
  • Michael Gruenstaeudl  · 技术社区  · 5 年前

    “1s”(其中 =3,例如)。

    > set.seed(123456789)
    > full=rep(0,100)
    > full[sample(1:100, 15)]=1
    > split(full, ceiling(seq_along(full)/10))
    $`1`
     [1] 0 0 0 0 0 1 0 0 0 0
    
    $`2`
     [1] 0 0 1 0 0 0 0 0 0 0
    
    $`3`
     [1] 0 0 1 0 1 0 0 0 0 0
    
    $`4`
     [1] 0 0 0 0 0 0 0 1 0 0
    
    $`5`
     [1] 0 1 0 0 0 0 0 0 1 0
    
    $`6`
     [1] 0 0 0 0 0 0 0 0 0 0
    
    $`7`
     [1] 0 0 0 0 1 0 1 0 0 1
    
    $`8`
     [1] 0 0 0 0 0 1 0 0 0 0
    
    $`9`
     [1] 0 0 0 0 0 1 1 0 1 0
    
    $`10`
     [1] 0 0 0 0 0 0 0 0 0 1
    

    > desired_function(full)
    61-70
    81-90  
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   akrun    5 年前

    rollsum )与 width 10,检查是否有3个1s(二进制数据),用 which cut 然后得到 unique 铲斗的值

    library(zoo)
    unique(cut(which(rollapply(full, 10, function(x) sum(x) == 3)), 
      breaks = c(-Inf, 11, 20, 31, 40, 51, 60), 
          labels = c('11-20', '21-30', '31-40', '41-50', '51-60', '61-70')))
    
        2
  •  2
  •   Allan Cameron    5 年前

    set.seed(123456789)
    
    full <- rep(0,100)
    full[sample(1:100, 15)] <- 1
    my_list <- split(full, ceiling(seq_along(full)/10))
    names(my_list) <- paste(10 * (as.numeric(names(my_list)) - 1) + 1, 
                            10 * (as.numeric(names(my_list)) - 1) + 10,
                            sep = " - ")
    names(which(sapply(my_list, function(x) sum(x) == 3)))
    #> [1] "21 - 30" "31 - 40"
    

    创建于2020-07-24 reprex package (0.3.0版)