0

I am trying to substitute values in a column of a data frame that meet a specific condition (in this example behavior == "X") for the previous value in the same column which is not X.

My data looks like the column behavior (see below) and I want to create a new column which need to be like the column behavior2 in which I have substituted the value X with previous known value of behavior which is not X.

What would be the R code to create such a new column in the data frame

Thanks for the help

> dat
    time behavior behavior2
1     0        A         A
2    50        B         B
3   100        B         B
4   150        C         C
5   200        B         B
6   250        A         A
7   300        X         A
8   350        A         A
9   400        A         A
10  450        A         A
11  500        B         B
12  550        X         B
13  600        X         B
14  650        A         A
15  700        C         C
16  750        A         A
17  800        B         B
18  850        X         B
19  900        B         B
20  950        A         A
21 1000        A         A
zx8754
  • 52,746
  • 12
  • 114
  • 209
larroca
  • 1
  • 1

0 Answers0