Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find last row per each column of dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading