Search code examples
rloopsmatrixapplymapply

R fill up matrix without using a loop


Hi everybody I'm looking for some coding advice and tricks. I have a 10x10 matrix like this:

mat <- matrix(NA, nrow = 10, ncol = 10)

and a function that takes two numbers and returns a simple scalar:

fct <- function(x1, x2){
return(x1 * x2)
}

My function is a bit more complexed but this is just for illustration purpose.

I would like to fill up the matrix mat by applying the function fct to two vectors, let's say:

x1 <- c(1:10)
x2 <- c(1:10)

I can easily do it with a loop but I was wondering if someone knew a better way, maybe using mapply/Map.

Thanks for your help!


Solution

  • Vectorizing the function like so:

    fct <- function(x1, x2){
    out <- numeric(length = length(x1))
    for(i in seq_along(x1)) {
        out[i] <- x1[i] * x2[i]
     }
    return(out)
    }
    

    Then applying outer:

    outer(x1, x2, fct)
    

    will do the trick!

    Thank you!