I have the following dataframe and i want to get a vector that contains the last non NA row of each column
df <- data.frame(a = 1:5, b = 6:10, c = c(rep(NA, 5)))
df <- rbind(df, rep(NA, ncol(df)), rep(NA, ncol(df)))
df[2,] <- NA
df$b[6]<-8
df
a b c
1 1 6 NA
2 NA NA NA
3 3 8 NA
4 4 9 NA
5 5 10 NA
6 NA 8 NA
7 NA NA NA
the vector im looking would be:
c(5,6,0)
how can i achieve this using base r? i have the following formula but throws me warnings:
apply(row(df) + 0 * df, 2, function(x) max(x, na.rm = TRUE))
thanks
>Solution :
sapply(df, function(z) c(rev(which(!is.na(z))), 0)[1])
# a b c
# 5 6 0