0

I have a data frame that looks like the following:

index    A    B    correct
1        1    1    -
2        1    2    -
3        1    3    0
4        2    1    -
5        2    2    -
6        2    3    1

I would like to propagate the value of 'correct' to other rows when A matches. I.e. the desired output:

index    A    B    correct
1        1    1    0
2        1    2    0
3        1    3    0
4        2    1    1
5        2    2    1
6        2    3    1

So all the rows that has A = 1 will have the same value of correct, which is propagated from row(A=1,B=3).

How should I do this in R? I have a big dataframe with many columns and it is seems that using loops to manipulate dataframes is not recommended in R. Any help would be greatly appreciated!

Hai
  • 163
  • 2
  • 7
  • 2
    Possible duplicate of [replace NA value with the group value](https://stackoverflow.com/questions/23583739/replace-na-value-with-the-group-value) – cmaher Feb 02 '18 at 17:13
  • What are those `-` in missing values in column `correct`? `NA`, empty, or actual `-`? Is there any chance that `correct` can take both `0` and `1` for a specific `A` value? – AntoniosK Feb 02 '18 at 17:14
  • Thanks for the quick response. `-` mean NA here, and can only be 0 and 1. I think what @cmaher pointed is the same problem. I actually had no idea how to phrase my question... – Hai Feb 02 '18 at 22:13

1 Answers1

1
 transform(A,correct=zoo::na.locf0(correct,T))
  index A B correct
1     1 1 1       0
2     2 1 2       0
3     3 1 3       0
4     4 2 1       1
5     5 2 2       1
6     6 2 3       1
Onyambu
  • 67,392
  • 3
  • 24
  • 53