nita
nita

Reputation: 85

How to cumulatively multiply vector without using cumprod in r?

I need to create a function cprod -> that takes a numeric vector as an argument and returns a cumulative vector of the same length. So, if I have cprod(c(1,2,3)), the returning vector should be c (1, 1 * 2, 1 * 2 * 3) = c (1, 2, 6).

Can this be done without cumprod? Maybe with prod or for-loop?

Upvotes: 7

Views: 595

Answers (6)

jay.sf
jay.sf

Reputation: 72974

An Rcpp variant.

library(Rcpp)
cppFunction('
NumericVector cumProd(NumericVector x) {
  int n = x.size();
  NumericVector out(n);
  out[0] = x[0];
  for(int i = 1; i < n; ++i) {
    out[i] = out[i - 1] * x[i];
  }
  return out;
}
')

cumProd(1:10)
# [1]       1       2       6      24     120     720    5040   40320  362880 3628800

stopifnot(all.equal(cumProd(1:10), cumprod(1:10)))

Upvotes: 0

AnilGoyal
AnilGoyal

Reputation: 26218

purrr may also help

x <- 1:5

purrr::accumulate(x, ~ .x*.y)

[1]   1   2   6  24 120

Upvotes: 1

pseudospin
pseudospin

Reputation: 2767

It doesn't use cumprod...

x <- c(1,2,3)
exp(cumsum(log(x)))

#> [1] 1 2 6

Upvotes: 6

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

Reduce(`*`, x, accumulate = TRUE)

[1] 1 2 6

Upvotes: 7

Roman Luštrik
Roman Luštrik

Reputation: 70633

Something like this?

> x <- 1:3
> cumprod(x)
[1] 1 2 6
> for (i in 2:length(x)) {
+   x[i] <- x[i-1] * x[i]
+ }
> x
[1] 1 2 6

Upvotes: 3

Duck
Duck

Reputation: 39595

Try this with a loop:

#Code
v1 <- c(1,2,3)
#Empty vector
v2 <- numeric(length(v1))
#Loop
for(i in 1:length(v1))
{
  #Move around each element
  e1 <- v1[1:i]
  #Compute prod
  vp <- prod(e1)
  #Save
  v2[i] <- vp
}

Output:

v2
[1] 1 2 6

Upvotes: 3

Related Questions