Create a function which returns cumulative sum of vector, without using cumsum in R

Viewed 105

I have to create a function that takes a numeric vector as an argument, and returns its cumulative sum as a vector of equal length.

I've been trying to figure this out for over 5 hours now, but I just can't do it for the life of me. Please note that I'm new to R. Please help me.

My attempt so far, with no success:

y <- function(x) {
    for (i in x) {
    
         print(sum(x[1]:x[i]):sum(x[1]:x[i]))
   }
}

also tried

y <- function(x) {
        for (i in x) {
        
             print(x[1]:sum(x[1]:x[i]))
       }
    }
1 Answers

A good practice might be using recursion (although it is inefficient)

csum <- function(x) {
  if (length(x) == 1) {
    return(x)
  }
  v <- Recall(head(x, -1))
  c(v, tail(v, 1) + tail(x, 1))
}

or a more efficient way using for loops

csum <- function(x) {
  if (length(x)==1) return(x)
  for (i in 2:length(x)) {
    x[i] <- sum(x[(i - 1):i])
  }
  x
}

or using lower.tri + tcrossprod

cumsum <- function(x) c(tcrossprod(lower.tri(diag(x), diag = TRUE), t(x)))

such that

> csum(1:10)
 [1]  1  3  6 10 15 21 28 36 45 55
Related