[R] how to select the last non-'NA' observation in a row

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Apr 20 10:41:29 CEST 2010


one way is the following:

a1 <- c(9,8,rep(NA,5))
a2 <- c(3,NA,3,NA,3,NA,4)
a3 <- c(11,6,7,NA,5,NA,6)
M <- rbind(a1,a2,a3)

ind <- !is.na(M)
tapply(M[ind], row(M)[ind], tail, 1)


I hope it helps.

Best,
Dimitris


On 4/20/2010 10:33 AM, gallon li wrote:
> I have a matrix of the following form:
>
>      time
> id    0  2  4  6  9 12 14
>    3   9  8 NA NA NA NA NA
>    7   3 NA  3 NA  3 NA  4
>    13 11  6  7 NA  5 NA  6
>   .....
>
> I hope for each row to select the last observation which is not 'NA'.
>
> For example, for the first row, id=3, the value I want to select is 8
> for the second row, id=7, the value I want to select is 4
> for the third row, id=13, the value I want to select is 6
>
> ....
>
> if it would be easier for you to demonstrate for me, here I include the code
> to generate the above three-row matrix:
>
> a1=c(9,8,rep(NA,5))
> a2=c(3,NA,3,NA,3,NA,4)
> a3=c(11,6,7,NA,5,NA,6)
> matrix=rbind(a1,a2,a3)
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014



More information about the R-help mailing list