Select last non-NA value in a row, by row

Do this by combining three things:

  • Identify NA values with is.na
  • Find the last value in a vector with tail
  • Use apply to apply this function to each row in the data.frame

The code:

lastValue <- function(x)   tail(x[!is.na(x)], 1)

apply(df, 1, lastValue)
[1] 2 6 3 4 1

Leave a Comment