vwrobel
vwrobel

Reputation: 1736

How to apply a bivariate function over the cross combination of two vectors to get a matrix in R?

Say I have two vectors:

a <- 1:4
b <- 1:2

and a bivariate function:

f <- function(x,y) x**y

I would like to get a simple and efficient way (a one-liner?) to get (for this specific example):

[,1] [,2]
[1,]    1    1
[2,]    2    4
[3,]    3    9
[4,]    4   16

I can do:

res <- matrix(nrow=length(a), ncol=length(b))
for (i in 1:length(b)){
  res[,i] <- mapply(f, a , b[i])
}

but I want to avoid loops.

Upvotes: 0

Views: 28

Answers (1)

LAP
LAP

Reputation: 6695

Just use lapply over one of the vectors, while setting the other as constant. Then cbind() the list with do.call():

test <- do.call(cbind, lapply(b, function(x) a**x))

> test
     [,1] [,2]
[1,]    1    1
[2,]    2    4
[3,]    3    9
[4,]    4   16

Upvotes: 2

Related Questions