Kingindanord
Kingindanord

Reputation: 2036

How to apply a function on every possible combination of two columns in two matrices in R

I have two matrices each has 300 columns; M1 and M2 I am applying a simple ifelse function on them as following:

result<-ifelse(M1[-nrow(M1),]<M2[-nrow(M2),],1,4)


tail(result)


                    X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17
2017-06-26 04:00:00  4  1  1  4  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 05:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 06:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 07:00:00  4  1  1  1  4  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 08:00:00  4  1  1  1  1  4  4  4  4   4   4   4   4   4   4   4   4
2017-06-26 09:00:00  4  1  1  1  1  1  4  4  4   4   4   4   4   4   4   4   4

In this case the ifelse function applied on every column in M1 with it's matching column in M2

How can I apply the ifelse function on every possible combination of columns in M1 and M2 and save the results into one big matrix (90000 columns in this case) or list of matrices?

Upvotes: 1

Views: 72

Answers (1)

dbokers
dbokers

Reputation: 920

Using expand.grid to get a cartesian product of the column indices would help.

m1 <- matrix(1:9, ncol=3)
m2 <- matrix(4:12, ncol=3)
g <- expand.grid(1:nrow(m1), 1:ncol(m2))
ans <- ifelse(m1[, g[, 1]] < m2[, g[, 2]], 1, 4)

Upvotes: 3

Related Questions