0
votes

I want to create two matrices (say S and P) in one list (say myList), which each of them can take binary values and are diagonal matrices like this (T stands for TRUE and F stands for FALSE):

S:
S1  S2
T   F
F   T 

P:
P1 P2 P3
T  F  F
F  T  F
F  F  T

And then I want to create a matrix (or data.frame) that can show all combination of these two variables in a binary format. E.g. It should look like this:

S1 S2 P1 P2 P3
T   F  T  F  F
T   F  F  T  F
T   F  F  F  T
F   T  T  F  F
F   T  F  T  F
F   T  F  F  T
F   F  T  F  F
F   F  F  T  F
F   F  F  F  T

I have the size of each matrix in another list: myMatrixSizes

How can I do this in R?

I have tried this, but the results are not in the shape that I want:

lapply(
  lapply(
      c(myList),
      function(y) Diagonal(myMatrixSizes(y,myList)])==1
  ),
  function(x) lapply(x,2, rep, prod(myMatrixSizes)/ dim(x)[1])
)

Thanks!

1
How do you get 9 rows when getting every combination of (2vars * 3vars)? - thelatemail

1 Answers

2
votes

Something like this perhaps?

S <- data.frame(S1=c(TRUE,FALSE),S2=c(FALSE,TRUE))
P <- data.frame(P1=c(TRUE,FALSE,FALSE),P2=c(FALSE,TRUE,FALSE),P3=c(FALSE,FALSE,TRUE))

ids <- expand.grid(1:length(S),1:length(P))
t(mapply(function(x,y) unlist(c(S[x,],P[y,])) , ids[[1]], ids[[2]]))

        S1    S2    P1    P2    P3
[1,]  TRUE FALSE  TRUE FALSE FALSE
[2,] FALSE  TRUE  TRUE FALSE FALSE
[3,]  TRUE FALSE FALSE  TRUE FALSE
[4,] FALSE  TRUE FALSE  TRUE FALSE
[5,]  TRUE FALSE FALSE FALSE  TRUE
[6,] FALSE  TRUE FALSE FALSE  TRUE