The two pieces of code are different.
- The first one replace
NA
with the previous element if this one is not NA. - The second one replace
NA
with the previous element if this one is notNA
, but the previous element can be the result of a previousNA
substitution.
Which one is correct really depends on you. The second behaviour is more difficult to vectorize, but there are some already implemented functions like zoo::na.locf
.
Or, if you only want to use base packages, you could have a look at this answer.