Re: [R] cumsum while maintaining NA

From: Pete Brecknock <Peter.Brecknock_at_bp.com>
Date: Sat, 02 Apr 2011 14:26:40 -0500 (CDT)

Here's one way .....

Lines<-"x1 x2 x3 x4 x5 x6
NA NA 3 4 NA NA
5 3 4 NA NA NA
7 3 4 4 NA NA
11 3 4 5 NA NA
67 4 4 NA NA NA"

d <- read.table(textConnection(Lines), header = TRUE, colClasses=c("integer"))
closeAllConnections()

res = t(apply(d, 1, function(x) ave(x,is.na(x),FUN=cumsum)))

print(res)

     x1 x2 x3 x4 x5 x6
[1,] NA NA 3 7 NA NA
[2,] 5 8 12 NA NA NA
[3,] 7 10 14 18 NA NA
[4,] 11 14 18 23 NA NA
[5,] 67 71 75 NA NA NA

HTH Pete

--
View this message in context: http://r.789695.n4.nabble.com/cumsum-while-maintaining-NA-tp3421513p3422619.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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.
Received on Sat 02 Apr 2011 - 19:31:28 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 02 Apr 2011 - 20:00:26 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive