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
?
cumprod() function in R Language is used to calculate the cumulative product of the vector passed as argument.
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.
One option could be:
Reduce(`*`, x, accumulate = TRUE)
[1] 1 2 6
It doesn't use cumprod
...
x <- c(1,2,3)
exp(cumsum(log(x)))
#> [1] 1 2 6
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With