How do you find duplicated elements of a vector that outputs the integer appearance of that duplicate instead of a logical?

后端 未结 1 1125
情书的邮戳
情书的邮戳 2021-01-21 03:12

We know that the duplicated() function outputs a vector of logicals. What I want, however, is a vector of integers such that, if this is the (n+1)th time that this particular el

1条回答
  •  -上瘾入骨i
    2021-01-21 03:46

    Here's a possible solution using base R (not sure if vectorized enough for you)

    as.numeric(ave(x, x, FUN = seq)) - 1L
    ## [1] 0 0 1 0 1 2 1 3 4 2
    

    Or something similar using data.table package

    library(data.table)
    as.data.table(x)[, y := seq_len(.N) - 1L, by = x][]
    #     x y
    #  1: c 0
    #  2: b 0
    #  3: b 1
    #  4: a 0
    #  5: a 1
    #  6: b 2
    #  7: c 1
    #  8: b 3
    #  9: b 4
    # 10: c 2
    

    Or maybe a dplyr option

    library(dplyr)
    data.frame(x) %>%
      group_by(x) %>%
      mutate(y = row_number() - 1L)
    # Source: local data frame [10 x 2]
    # Groups: x
    # 
    #    x y
    # 1  c 0
    # 2  b 0
    # 3  b 1
    # 4  a 0
    # 5  a 1
    # 6  b 2
    # 7  c 1
    # 8  b 3
    # 9  b 4
    # 10 c 2
    

    0 讨论(0)
提交回复
热议问题