Home > OS >  How do I crate a row which has the value of the last time a condition was met in a separate row in R
How do I crate a row which has the value of the last time a condition was met in a separate row in R

Time:10-13

I have data that looks like this:

d <- data.frame(Item = c(1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0)

I would like to create a row where the value is based on the last time a 0 was present in the row d$item. I don't really know how to get started with something like this in R.

CodePudding user response:

You can do this, with sequence. It calculate the distance to the latest 1.

dif <- diff(c(which(d$Item == 1), length(d$Item)   1))
sequence(dif, 0)
#[1] 0 1 2 0 0 0 0 0 0 1 2 0 1 0 0 0 1

CodePudding user response:

You can try gregexpr to capture the positions of last 0s before 1s, e.g.,

transform(
  d,
  lastZero = replace(
    rep(0, length(Item)),
    unlist(gregexpr("0(?=1)|0$", paste0(Item, collapse = ""), perl = TRUE)), 
    1
  )
)

which gives

   Item lastZero
1     1        0
2     0        0
3     0        1
4     1        0
5     1        0
6     1        0
7     1        0
8     1        0
9     1        0
10    0        0
11    0        1
12    1        0
13    0        1
14    1        0
15    1        0
16    1        0
17    0        1
  •  Tags:  
  • r
  • Related