Search code examples
rgroup-bylag

Create new column and carry forward value from previous group to next


I am trying to carry forward value from the previous group to the next group. I tried to solve it using rleid but that could not get the desired result.

df <- data.frame(signal = c(1,1,5,5,5,2,3,3,3,4,4,5,5,5,5,6,7,7,8,9,9,9,10), 
                 desired_outcome = c(NA, NA, 1, 1, 1, 5, 2, 2, 2, 3, 3, 4, 4,4,4,5,6,6,7,8,8,8,9))

# outcome column has the expected result -
   signal desired_outcome
1       1              NA
2       1              NA
3       5               1
4       5               1
5       5               1
6       2               5
7       3               2
8       3               2
9       3               2
10      4               3
11      4               3
12      5               4
13      5               4
14      5               4
15      5               4
16      6               5
17      7               6
18      7               6
19      8               7
20      9               8
21      9               8
22      9               8
23     10               9

Solution

  • rle will give the lengths and values of sequences where the same value occur. Then: remove the last value, shift remaining values one over, add an NA to the beginning of the value to account for removing the last value, and repeat each value as given by lengths (i.e. the lengths of sequences of same value in the original vector).

    with(rle(df$signal), rep(c(NA, head(values, -1)), lengths))
    # [1] NA NA  1  1  1  5  2  2  2  3  3  4  4  4  4  5  6  6  7  8  8  8  9