cumsum along row of data.frame with NA in R

后端 未结 2 469
孤独总比滥情好
孤独总比滥情好 2021-01-23 05:54

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 <-         


        
相关标签:
2条回答
  • 2021-01-23 06:22

    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)))
    
    0 讨论(0)
  • 2021-01-23 06:26

    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))
    
    0 讨论(0)
提交回复
热议问题