R - Loop through different matrices without using loop ! Help to simply a code -
so have 2 separate matrix (mat1 , mat2) , need go through them in order make check. need store results third matrix.
i feel code long purpose.
i wanted have of suggestion avoid looping.
so first matrix looks (dput in end)
wit5.001 wit5.002 wit5.003 wit5.004 wit5.005 wit5.006 wit5.007 wit5.008 wit5.009 wit5.010 [1,] 1 1 1 1 1 1 1 1 1 1 [2,] 1 1 1 1 1 1 1 1 1 1 [3,] 1 1 1 1 1 1 1 1 1 1 [4,] 1 1 1 1 1 1 1 1 1 1 [5,] 1 1 1 1 1 1 1 0 1 1 [6,] 1 1 1 1 1 1 1 0 0 0 [7,] 0 1 1 1 1 1 1 1 1 1 [8,] 1 1 1 1 1 1 1 1 1 1 [9,] 1 1 1 1 1 1 1 1 1 1 [10,] 1 1 1 1 1 1 1 1 1 1
my second matrix has similar structure.
here create third matrix - in order store results of checking.
matcheck <- matrix('ok', ncol = ncol(mat1), nrow = nrow(mat1))
here loop - avoid
for(j in 1:ncol(mat1)){ for(i in 1:nrow(mat1)){ if(mat1[i,j] == 1 & mat2[i,j] == 1) {matcheck[i,j] <- 'ok'} if(mat1[i,j] != 1 & mat2[i,j] == 1) {matcheck[i,j] <- '!'} } }
the result of check
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [2,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [3,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [4,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [5,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [6,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "!" "!" "ok" [7,] "!" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [8,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [9,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" [10,] "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok" "ok"
any suggestions ?
here matrix 1
mat1 = structure(c(1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1), .dim = c(10l, 10l), .dimnames = list(null, c("wit5.001", "wit5.002", "wit5.003", "wit5.004", "wit5.005", "wit5.006", "wit5.007", "wit5.008", "wit5.009", "wit5.010")))
here matrix 2
mat2 = structure(c(1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), .dim = c(10l, 10l), .dimnames = list(null, c("wit5.020", "wit5.021", "wit5.022", "wit5.023", "wit5.024", "wit5.025", "wit5.026", "wit5.027", "wit5.028", "wit5.029")))
for example given, result can constructed as
matcheck <- ( mat1 | !mat2 )
this equivalent initializing matcheck
true , filling in false !mat1 & mat2
(as in op's loop). parentheses optional, make easier read (i think).
Comments
Post a Comment