简体   繁体   English

创建一个返回向量累积和的函数,而不在 R 中使用 cumsum

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

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.我已经尝试了 5 个多小时来解决这个问题,但我这辈子都做不到。 Please note that I'm new to R. Please help me.请注意,我是 R 新手。请帮助我。

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]))
       }
    }

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或更有效的方式使用for循环

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或使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM