我想定义一个从1开始计数的变量,并根据另一列的变化重新开始。我确信这已经得到了回答,但我在搜索成功方面遇到了困难。
示例数据: 是myDF:
ID DOSE
1 AC09 0.1
2 AH01 0.1
3 CH01 0.1
4 AB09 1
5 AA09 10
6 BG02 0.1
7 BF02 1
8 AD01 10
9 CD01 10
我订购的数据是这样的,我想根据DOSE的变化计算复制数并重新开始,如下所示:
ID DOSE REP
1 AC09 0.1 1
2 AH01 0.1 2
3 CH01 0.1 3
4 AB09 1 1
5 AA09 10 1
6 BG02 0.1 1
7 BF02 1 1
8 AD01 10 1
9 CD01 10 2
我尝试使用重复和滞后函数,但无法获得正确的语法。
> mydf$dups <- !duplicated(mydf[,2])
> mydf$reps <- ifelse(mydf$dups == 1, 1, lag(mydf$dups)+1)
> mydf
ID DOSE dups reps
1 AC09 0.1 TRUE 1
2 AH01 0.1 FALSE 2
3 CH01 0.1 FALSE 1
4 AB09 1 TRUE 1
5 AA09 10 TRUE 1
6 BG02 0.1 FALSE 2
7 BF02 1 FALSE 1
8 AD01 10 FALSE 1
9 CD01 10 FALSE 1
mydf <- structure(list(ID = c("AC09", "AH01", "CH01", "AB09", "AA09", "BG02", "BF02", "AD01", "CD01"),DOSE = c("0.1", "0.1", "0.1", "1", "10", "0.1", "1", "10", "10")), row.names=c(1:9),.Names = c("ID", "DOSE"), class = "data.frame")
mydf