Row-wise backward cumulative product/multiplication for a matrix

Viewed 53

I have a matrix x:

x <- matrix(1:8, nrow = 2, ncol = 4, byrow = 2)
#   [,1] [,2] [,3] [,4]
#[1,] 1    2    3    4 
#[2,] 5    6    7    8

I want to get a new matrix y:

#     [,1] [,2] [,3] [,4]
#[1,]  24   24   12    4
#[2,] 1680 336   56    8

The logic is (taking the 1st row for example):

y[1, 1] = prod(x[1, 1:4])
y[1, 2] = prod(x[1, 2:4])
y[1, 3] = prod(x[1, 3:4])
y[1, 4] = prod(x[1, 4:4])

I know the prod function works if I want to multiply the entire row, but I can't figure out how to do the sequential multiplication I mentioned above.

1 Answers

Without any additional packages:

ind <- ncol(x):1
t(apply(x[, ind], 1, cumprod))[, ind]
#     [,1] [,2] [,3] [,4]
#[1,]   24   24   12    4
#[2,] 1680  336   56    8

More efficiently with matrixStats package:

ind <- ncol(x):1
matrixStats::rowCumprods(x, cols = ind)[, ind]
#     [,1] [,2] [,3] [,4]
#[1,]   24   24   12    4
#[2,] 1680  336   56    8
Related