I have this dataframe:
dat <- data.frame(Var1 = c(1,1,1,1,2,2,3,3,3,3,3,3,4,4,4,5,5,5,5))
> dat
Var1
1 1
2 1
3 1
4 1
5 2
6 2
7 3
8 3
9 3
10 3
11 3
12 3
13 4
14 4
15 4
16 5
17 5
18 5
19 5
I want to get the row numbers where a new value appears for the first time.
The result should be:
c(1, 5, 7, 13, 16)
I got as far as identifying the unique values with unique(dat$Var1)
and finding the first row for one value with min(which(dat$Var1 == 1))
, but I don't know how to combine the two without using a loop.
Ideally I'm looking for a solution in base R, unless the solution in some package is extremely simple (e.g. some.function(dat$Var1)
).
rle
! And a very clever use ofcumsum
andhead
! – Strung