Zuhaib Ahmed
Zuhaib Ahmed

Reputation: 497

R: Repeatedly apply function to corresponding elements of matrices, and collect the result

I'd like to apply some function to corresponding elements of some matrices (of the same size), and to return the result of each application, so that I can add it to some accumulator. The most intuitive way to do this is with a loop, but I'm working with large data sets, and loops take too long.

I'm aware of the apply class of functions, but I'm not quite sure how to use them to accumulate the result from each iteration.

Here's a small example of what I'm trying to do.

mat <- matrix(c(0, 1, 2, 3, 2, 9, 5, 1, 1, 1, 0, 0, 5, 5, 2, 0), 4, 4)
mat2 <- matrix(c(1, 1, 3, 1, 6, 2, 9, 2, 0, 1, 3, 2, 0, 1, 2, 1), 4, 4)
mat3 <- matrix(c(0, 4, 6, 1, 0, 4, 3, 8, 9, 1, 3, 0, 9, 9, 8, 8), 4, 4)

some_function <- function(num1, num2, num3) {
  return(num1 * num2 + num3)    
}

accum <- 0.1
for (i in 1:nrow(mat)) {
  for (j in 1:ncol(mat)) {
    accum <- accum + log(1 + some_function(mat[i,j], mat2[i,j], mat3[i,j]+10))
  }
}

This gives the correct answer, but I'd like to do this without loops. Also note that some_function is just an arbitrary function that I'm putting for the sake of example. The function that I'm applying to my data is more complicated.

Upvotes: 0

Views: 111

Answers (1)

Gonzalo Falloux Costa
Gonzalo Falloux Costa

Reputation: 372

You dont need apply for this, just run the function.

accum <- 0.1+sum(log(1+(some_function)(mat,mat2,mat3+10)))

is way faster and cleaner.

Upvotes: 1

Related Questions