使用 R 将前几行的正值分组,然后是另一组负值的行,依此类推

Grouping first few rows with positive value followed by another group with negative values and so on using R

我的数据框如下所示:

name       strand

thrL       1

thrA       1

thrB       1

yaaA       -1

yaaJ       -1

talB       1

mog        1

我想将前几个正值分组为一组,将负值分组为一组,然后将下一个正数分组为另一组,如下所示:

name       strand     directon

thrL       1           1

thrA       1           1

thrB       1           1

yaaA       -1          2

yaaJ       -1          2

talB       1           3

mog        1           3

我正在考虑使用 dplyr,但我需要一些有关使用 R 的代码的帮助。非常感谢。

使用rle

df$direction <- with(rle(sign(df$strand)), rep(seq_along(values), lengths))
df

#  name strand direction
#1 thrL      1         1
#2 thrA      1         1
#3 thrB      1         1
#4 yaaA     -1         2
#5 yaaJ     -1         2
#6 talB      1         3
#7  mog      1         3

这可以通过 data.table rleid 缩短。

df$direction <- data.table::rleid(sign(df$strand))

我们也可以这样做

df1$direction <- inverse.rle(within.list(rle(sign(df1$strand)),
         values <- seq_along(values)))
df1$direction
#[1] 1 1 1 2 2 3 3

数据

df1 <- structure(list(name = c("thrL", "thrA", "thrB", "yaaA", "yaaJ", 
"talB", "mog"), strand = c(1L, 1L, 1L, -1L, -1L, 1L, 1L)), 
class = "data.frame", row.names = c(NA, 
-7L))