How to find first element of a group that fulfill a condition

后端 未结 3 473
感动是毒
感动是毒 2021-01-20 12:35
structure(list(group = c(17L, 17L, 17L, 18L, 18L, 18L, 18L, 19L, 
19L, 19L, 20L, 20L, 20L, 21L, 21L, 22L, 23L, 24L, 25L, 25L, 25L, 
26L, 27L, 27L, 27L, 28L), var = c         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 13:03

    For ungrouped data, one solution is

    first_equal_to = function(x, value)
        (x == value) & (cumsum(x == value) == 1)
    

    so

    tbl %>% group_by(group) %>% mutate(first = first_equal_to(var, 1))
    

    (it seems appropriate to keep this as a logical vector, since that is what the column represents).

    Another implementation is

    first_equal_to2 = function(x, value) {
        result = logical(length(x))
        result[match(value, x)] = TRUE
        result
    }
    

提交回复
热议问题