29

data.tablerleid为运行长度编码提供了一个很好的便利功能:

library(data.table)
DT = data.table(grp=rep(c("A", "B", "C", "A", "B"), c(2, 2, 3, 1, 2)), value=1:10)
rleid(DT$grp)
# [1] 1 1 2 2 3 3 3 4 5 5

我可以在基础R上模仿这个:

df <- data.frame(DT)
rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)
# [1] 1 1 2 2 3 3 3 4 5 5

有谁知道dplyr等效的(?)或者是创建rleid行为的“最佳”方法dplyr是执行以下操作

library(dplyr)

my_rleid = rep(seq_along(rle(df$grp)$values), times = rle(df$grp)$lengths)

df %>%
  mutate(rleid = my_rleid)
4

4 回答 4

27

您可以这样做(当您同时加载时):

DT <- DT %>% mutate(rlid = rleid(grp))

这给出了:

> DT
    grp value rlid
 1:   A     1    1
 2:   A     2    1
 3:   B     3    2
 4:   B     4    2
 5:   C     5    3
 6:   C     6    3
 7:   C     7    3
 8:   A     8    4
 9:   B     9    5
10:   B    10    5

当您不想单独加载时,您也可以使用(如评论中@DavidArenburg 所述):

DT <- DT %>% mutate(rlid = data.table::rleid(grp))

正如@RichardScriven 在他的评论中所说,您可以复制/窃取它:

myrleid <- data.table::rleid
于 2015-11-03T20:04:46.180 回答
19

If you want to use just base R and dplyr, the better way is to wrap up your own one or two line version of rleid() as a function and then apply that whenever you need it.

library(dplyr)

myrleid <- function(x) {
    x <- rle(x)$lengths
    rep(seq_along(x), times=x)
}

## Try it out
DT <- DT %>% mutate(rlid = myrleid(grp))
DT
#   grp value rlid
# 1:   A     1    1
# 2:   A     2    1
# 3:   B     3    2
# 4:   B     4    2
# 5:   C     5    3
# 6:   C     6    3
# 7:   C     7    3
# 8:   A     8    4
# 9:   B     9    5
#10:   B    10    5
于 2015-11-03T22:04:44.693 回答
9

您可以lag使用dplyr.

DT <-
    DT %>%
    mutate(rleid = (grp != lag(grp, 1, default = "asdf"))) %>%
    mutate(rleid = cumsum(rleid))

> DT
    grp value rleid
 1:   A     1     1
 2:   A     2     1
 3:   B     3     2
 4:   B     4     2
 5:   C     5     3
 6:   C     6     3
 7:   C     7     3
 8:   A     8     4
 9:   B     9     5
10:   B    10     5
于 2015-11-03T23:04:51.483 回答
6

OP 使用的方法的简化(不涉及额外的包)可能是:

DT %>%
 mutate(rleid = with(rle(grp), rep(seq_along(lengths), lengths)))

   grp value rleid
1    A     1     1
2    A     2     1
3    B     3     2
4    B     4     2
5    C     5     3
6    C     6     3
7    C     7     3
8    A     8     4
9    B     9     5
10   B    10     5

或者:

DT %>%
 mutate(rleid = rep(seq(ls <- rle(grp)$lengths), ls))
于 2019-05-04T08:45:56.560 回答