简体   繁体   中英

How to get m x k Matrix from n x m and n x k Matrices

No sure how to specify the question, but say I have sparse matrix:

i<-c(1,5,2,4,2,2,8)
j<-c(2,5,3,2,4,2,4)
set.seed(1234)
x<-rpois(7,2)
M1<-sparseMatrix(i,j,x=x)
rownames(M1) <- c("g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8")
colnames(M1) <- c("c1", "c2", "c3", "c4", "c5")
M1<- drop0(M1)

which gives

> M1 
8 x 5 sparse Matrix of class "dgCMatrix"
   c1 c2 c3 c4 c5
g1  .  .  .  .  .
g2  .  2  2  4  .
g3  .  .  .  .  .
g4  .  2  .  .  .
g5  .  .  .  .  2
g6  .  .  .  .  .
g7  .  .  .  .  .
g8  .  .  .  .  .

and another Matrix:

set.seed(1)
M2<-matrix(sample(0:3,24,replace=TRUE),nrow=8, ncol = 3)
rownames(M2) <- c("g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8")
colnames(M2) <- c("L1", "L2", "L3")

which gives

> M2
   L1 L2 L3
g1  0  1  1
g2  3  1  1
g3  2  2  1
g4  0  2  2
g5  1  0  0
g6  0  0  2
g7  2  0  0
g8  2  1  0

how would i one-hot a new matrix for c by L (mxk), to find where c is present in L based on g? I want to get:

> M2
   L1 L2 L3
c1  0  0  0
c2  1  1  1
c3  1  1  1
c4  1  1  1
c5  1  0  0

Where because c2,c3,c4 all share g2 and g2 is found in L1,L2,L3; then c2,c3,c4 will also span L1-L3. Since c5 is only associated with g5, and g5 is only in L1, then c1 is in L1 only. I was trying to use the ifelse() in a for loop like:

newMat <- Matrix(0, nrow = ncol(M1), ncol = ncol(M2))
for (i in 1:ncol(M1)){
  for (j in 1:ncol(M2)){
    newMat[i,j] <- ifelse(test = M2[i,j] > 0,
                              yes = 1,
                              no = 0)
  }
}

But this is not the right approach.... sorry if this question isn't clear.

Maybe you can try crossprod like below

> 1 * (crossprod(M1, M2) > 0)
5 x 3 Matrix of class "dgeMatrix"
   L1 L2 L3
c1  0  0  0
c2  1  1  1
c3  1  1  1
c4  1  1  1
c5  1  0  0

If you want to use for loops, you can try

newMat <- Matrix(0,
  nrow = ncol(M1),
  ncol = ncol(M2),
  dimnames = list(colnames(M1), colnames(M2))
)
for (i in 1:ncol(M1)) {
  for (j in 1:ncol(M2)) {
    newMat[i, j] <- ifelse(sum(M1[, i] * M2[, j] != 0), 1, 0)
  }
}

which gives

> newMat
5 x 3 sparse Matrix of class "dgCMatrix"
   L1 L2 L3
c1  .  .  .
c2  1  1  1
c3  1  1  1
c4  1  1  1
c5  1  .  .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM