Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cumulatively multiply vector without using cumprod in r?

Tags:

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?

like image 934
nita Avatar asked Sep 19 '20 13:09

nita


People also ask

What does Cumprod do in R?

cumprod() function in R Language is used to calculate the cumulative product of the vector passed as argument.

Which one of the following function is used to get cumulative product?

The cumprod() function is used to get cumulative product over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative product.


3 Answers

One option could be:

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

[1] 1 2 6
like image 102
tmfmnk Avatar answered Nov 10 '22 15:11

tmfmnk


It doesn't use cumprod...

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

#> [1] 1 2 6
like image 25
pseudospin Avatar answered Nov 10 '22 15:11

pseudospin


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
like image 40
Duck Avatar answered Nov 10 '22 15:11

Duck