The hypothetical case is that there exist NA in a data.frame
> a <- c(1:5, NA, 7:10)
> b <- 1:10
> c <- 1:10
>
> data <-
Given your desired result (where you don't mind NA
becoming 0
), I guess the easiest thing is to first remove the NA
values using is.na
and then carry on as before.
data[ is.na(data) ] <- 0
data.frame(t(apply(data,1,cumsum)))
Simon's is definitely the simplest. I was surprised to learn a few things from this exercise:
1. cumsum
doesn't have a na.rm
argument
2. sum(NA, na.rm=TRUE)
equals 0
Here is the code that brought me to the same solution:
cumsum.alt <- function(x){
res <- NaN*seq(x)
for(i in seq(x)){
res[i] <- sum(x[1:i], na.rm=TRUE)
}
res
}
t(apply(data, 1, cumsum.alt))
To return the NA´s, a slight modification can be used:
cumsum.alt <- function(x){
res <- NaN*seq(x)
for(i in seq(x)){
if(sum(is.na(x[1])) == i){
res[i] <- NaN
} else {
res[i] <- sum(x[1:i], na.rm=TRUE)
}
}
res
}
t(apply(data, 1, cumsum.alt))