How to create binary matrix from numerical matrix in R? -
pseudocode matrix operation try find out
- if matrix cell value < alpha, put 1.
- else 0.
i want create binary matrix alpha p-value matrix p.mat
cannot handle apply
correctly try satisfy pseudocode.
first approach
# http://stackoverflow.com/a/4236383/54964 new <- apply(p.mat.p, 1, function(x) if (alpha > x) { x <- 0 } else { x <- 1 } )
second approach fails
new <- apply(p.mat.p, 1, function(x) x <- (x < alpha) ) print(new) #error in match.fun(fun) : argument "fun" missing, no default #calls: apply -> match.fun #execution halted
trial , code
library("psych") ids <- seq(1,11) m.cor <- cor(mtcars) colnames(m.cor) <- ids rownames(m.cor) <- ids p.mat <- psych::corr.test(m.cor, adjust = "none", ci = f) p.mat.p <- p.mat[["p"]] alpha <- .00000005 # http://stackoverflow.com/a/4236383/54964 new <- apply(p.mat.p, 1, function(x) if (alpha > x) { x <- 0 } else { x <- 1 } ) #error in alpha > x : # comparison (6) possible atomic , list types #calls: sapply -> lapply -> fun #execution halted
example square matrix , p-value alpha.
input: nxn matrix p-value = p.mat.p
# str(p.mat.p) num [1:11, 1:11] 0.00 4.04e-09 1.09e-09 4.32e-06 1.78e-05 ... - attr(*, "dimnames")=list of 2 ..$ : chr [1:11] "1" "2" "3" "4" ... ..$ : chr [1:11] "1" "2" "3" "4" ... # 1 2 3 4 5 #1 0.000000e+00 4.037623e-09 1.091445e-09 4.322152e-06 1.780708e-05 #2 4.037623e-09 0.000000e+00 1.659424e-09 5.625666e-07 5.174268e-05 #3 1.091445e-09 1.659424e-09 0.000000e+00 1.304240e-05 4.935086e-06 ...
expected output: nxn binary matrix of ones , zeros, alpha=0.2 , intended output is
[,1] [,2] [,3] [,4] [,5] [1,] false true false true false [2,] true true true true true [3,] true true true true true
r: 3.3.1
os: debian 8.5
do
alpha <- .00000005 p.mat.p <- (p.mat.p < alpha) str(p.mat.p) print(p.mat.p)
output
logi [1:11, 1:11] true true true false false true ... - attr(*, "dimnames")=list of 2 ..$ : chr [1:11] "1" "2" "3" "4" ... ..$ : chr [1:11] "1" "2" "3" "4" ... 1 2 3 4 5 6 7 8 9 10 11 1 true true true false false true false false false false false 2 true true true false false false false false false false false 3 true true true false false true false false false false false 4 false false false true false false false true false false false 5 false false false false true false false false false false false 6 true false true false false true false false false false false 7 false false false false false false true false false false false 8 false false false true false false false true false false false 9 false false false false false false false false true false false 10 false false false false false false false false false true false 11 false false false false false false false false false false true
Comments
Post a Comment