5

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

2 Answers 2

4

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
1
  • Agreed with @camille, neat solution but code-only answers are frowned upon =(
    – Parfait
    Commented Aug 19, 2019 at 1:51
2

Another way could be to first lag signal then use rleid to create groups and use mutate to broadcast first value of each group to all the values.

library(dplyr)

df %>%
   mutate(out = lag(signal)) %>%
   group_by(group = data.table::rleid(signal)) %>%
   mutate(out = first(out)) %>%
   ungroup() %>%
   select(-group)


# A tibble: 23 x 2
#   signal   out
#    <dbl> <dbl>
# 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
# … with 13 more rows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.