a1=c('USA',9,8,rep(NA,5))
a2=c('CHN',NA,NA,3,NA,3,NA,4)
a3=c('JPN',11,6,7,NA,5,NA,NA)
M=rbind(a1,a2,a3)
colnames(M) <- c('country', '2008', '2009', '2010', '2011', '2012', '2013', '2014')
Hi, I want to find the length from column 2008 to the last non-na value for each row. The expected result is: USA 2 CHN 7 JPN 5
This is where I am now. I found the value of last non-NA value for each row, but what should I next?
ind <- !is.na(M)
tapply(M[ind], row(M)[ind], tail, 1)
max.col(!is.na(M[,-1]), 'last')
– akrunwhich
is another way.f <- function(x) rev(which(!is.na(x)))[1]
, thentapply(M[,-1],row(M[,-1]),f)
– Brian Davis