1

I want to make pair-wise products of variable numbers of matrices/vectors in base R. I only have this ugly solution (ugly is <<-) but intuitively think a nicer - maybe recursive - way exists, or perhaps even a function. I need a pair-wise version of prod.

f1 <- function(...) {
  input <- list(...)
  output <- input[[1]]
  sapply(2:length(input), function(m) output <<- output*input[[m]])
  return(output)
}

m1 <- matrix(1:6, ncol = 2)
m2 <- matrix(6:1, ncol = 2)
m3 <- 1/matrix(6:1, ncol = 2)

all(f1(m1,m2,m3) == m1*m2*m3) #[1] TRUE
user3375672
  • 3,728
  • 9
  • 41
  • 70

1 Answers1

2

Use Reduce :

f1 <- function(...) {
  Reduce(`*`, list(...))
}

all(f1(m1,m2,m3) == m1*m2*m3)
#[1] TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213