我有一个数据帧,如下所示:
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))