根据dplyr

时间:2018-06-10 15:07:12

标签: r filter dplyr

示例数据:

y <- c(sort(sample(0:100, 365,replace = T)),sort(sample(0:100, 365,replace = T)))
df <- data.frame(loc.id = rep(1:2,each = 365), day = rep(1:365,times = 2), y = y,ref.day = 250)

我想选择y> gt的所有第一行20,y> 40,y> 60和y>每个loc.id

80
df %>% group_by(loc.id) %>% dplyr::filter(any(y > 20)) %>% # additional check
    dplyr::slice(unique(c(which.max(y > 20), which.max(y > 40),which.max(y > 60),which.max(y > 80)))) %>% ungroup() 

    # A tibble: 8 x 4
      loc.id   day     y ref.day
      <int> <int> <int>   <dbl>
    1      1    78    21     250
    2      1   154    41     250
    3      1   225    61     250
    4      1   288    81     250
    5      2    79    21     250
    6      2   147    41     250
    7      2   224    61     250
    8      2   300    81     250

我想要添加一个额外的声明,即切片day之后是&gt; ref.day,然后选择day等于ref.day的行。 在这种情况下,它看起来像:

  # A tibble: 8 x 4
        loc.id   day    y ref.day
        <int> <int> <int>   <dbl>
    1      1    78    21     250
    2      1   154    41     250
    3      1   225    61     250
    4      1   288    81     250 # this row will not be selected. Instead row where day == 250 will be here instead 
    5      2    79    21     250
    6      2   147    41     250
    7      2   224    61     250
    8      2   300    81     250 # this row will not be selected. Instead row where day == 250 will be here instead

0 个答案:

没有答案