代码之家  ›  专栏  ›  技术社区  ›  89_Simple

在dplyr中选择特定行

  •  0
  • 89_Simple  · 技术社区  · 6 年前

    样本数据:

    dat <- structure(list(value = c(860L, 860L, 835L, 835L, 870L, 820L, 820L, 850L, 850L, 810L,
                                     852L, 840L, 840L, 825L, 825L, 900L, 900L, 830L,
                                     830L, 865L, 865L, 822L, 822L, 882L, 882L, 867L, 867L, 725L,
                                     725L, 727L, 727L, 874L, 874L), 
                      loc.id = c(12L, 13L, 12L, 13L, 12L, 12L, 13L, 12L, 13L, 12L,
                                 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 
                                 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L, 12L, 13L)), 
                      class = "data.frame", row.names = c(NA, -33L))
    
    dat <- dat %>% dplyr::arrange(loc.id, value)
    
    dat <- dat %>% dplyr::group_by(loc.id) %>% dplyr::mutate(length.val = n()) %>% dplyr::mutate(points.l = ceiling(length.val/4))
    


    1) 第一行是行号,
    2) 第1行+第1点,如果位置12是第6行,

    4) 最后一行是第17行。类似于:

      dat %>% group_by(loc.id) %>% 
                dplyr::filter(row_number() == 1st row,
                              row_number() == 1st row + points.l,
                              row_number() == last row - points.l,
                              row_number() == last row)
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Nicolas2    6 年前

     dat %>% group_by(loc.id) %>% filter(row_number() %in% c(1,1+points.l,n()-points.l,n()))