Nikitau
Nikitau

Reputation: 371

How to get first occurrence of repeated value in R?

So I have data that looks something like this:

01/01   1 <= saves row index
01/02   1
01/03   1
01/04   1
01/05   0
01/06   1 <= saves row index
01/07   1
01/08   -1
01/09   1 <= saves row index
01/10   1

And I want R to return the first row that begins the repetition of 1s. So I want output such that:

[1] 1 6 9

I can't quite figure out to get this. Help would be much appreciated!

Upvotes: 0

Views: 317

Answers (2)

akrun
akrun

Reputation: 887048

We can use rleid

library(data.table)
setDT(df1)[, if(all(v1==1)) .I[1L] , rleid(v1)]$V1
#[1] 1 6 9

Or with base R

with(df1, which(c(TRUE, v1[-1] !=  v1[-nrow(df1)]) & v1==1))
#[1] 1 6 9

data

df1 <- structure(list(date = c("01/01", "01/02", "01/03", "01/04", "01/05", 
"01/06", "01/07", "01/08", "01/09", "01/10"), v1 = c(1L, 1L, 
1L, 1L, 0L, 1L, 1L, -1L, 1L, 1L)), .Names = c("date", "v1"), 
class = "data.frame", row.names = c(NA, -10L))

Upvotes: 1

Marius
Marius

Reputation: 60060

In words you can say: "x equals 1 and has just changed", i.e.:

df = data.frame(
    time = paste0("01/0", 1:9),
    x = c(1, 1, 1, 1, 0, 1, 1, -1, 1)
)

which(
    # x equals 1
    (df$x == 1) &
    # x has changed (always treat as true for first x)
    (c(1, diff(df$x)) != 0 )
)

Upvotes: 4

Related Questions