[R] cumsum while maintaining NA

Pete Brecknock Peter.Brecknock at bp.com
Sat Apr 2 21:26:40 CEST 2011


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.



More information about the R-help mailing list