I have the following data frame -

```
 x <- c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
 y <- c(0,0,0,1,0,-1,0,-1,0,1,0,-1,0,1,0,0,0)
 data <- data.frame(x,y)

```

and I would like to create a type of momentum indicator. Effectively, if y is non-zero, x takes y's value and if y is 0, x takes on the value of the lagged x value. Essentially, I am replacing x's value row by row. Doing this in a for loop is simple -

```
 for (i in 1:nrow(data)) {
   data$x[i] <-
     ifelse(data$y[i] == 1, 1, ifelse(data$y[i] == -1, -1, data$x[i-1]))}

```

Giving me this output (what I am looking for)

```
    x  y
1  NA  0
2  NA  0
3  NA  0
4   1  1
5   1  0
6  -1 -1
7  -1  0
8  -1 -1
9  -1  0
10  1  1
11  1  0
12 -1 -1
13 -1  0
14  1  1
15  1  0
16  1  0
17  1  0

```

However, on really large datasets, this for loop is extremely inefficient. I'd like to implement this in dplyr, however the best solution I have managed to come up with does not do the trick

```
 data2 <- data.frame(x,y)

 data2 <- 
   data2 %>% 
   mutate(x = ifelse(y == 1, 1, ifelse(y == -1, 0, Lag(x))))

```

which return this

```
    x  y
1  NA  0
2   1  0
3   1  0
4   1  1
5   1  0
6   0 -1
7   1  0
8   0 -1
9   1  0
10  1  1
11  1  0
12  0 -1
13  1  0
14  1  1
15  1  0
16  1  0
17  1  0

```

My guess is that the way I am currently attempting to do this in dplyr does not control for the iterative nature of what I want to do, namely replace x as I move down the rows. Does anyone have ideas as to how I could do this through dplyr?