Do this by combining three things:
- Identify
NA
values withis.na
- Find the last value in a vector with
tail
- Use
apply
to apply this function to each row in thedata.frame
The code:
lastValue <- function(x) tail(x[!is.na(x)], 1)
apply(df, 1, lastValue)
[1] 2 6 3 4 1