[R] threshold matrix
Petr Savicky
savicky at praha1.ff.cuni.cz
Fri Apr 29 17:09:58 CEST 2011
On Fri, Apr 29, 2011 at 07:44:59AM -0700, Alaios wrote:
> Thanks a lot.
> I finally used
>
> M2 <- M
> M2[M < thresh] <- 0
> M2[M >= thresh] <- 1
>
> as I noticed that this one line
>
> M2 <- as.numeric( M[] < thresh )
> vectorizes my matrix.
Hi.
This may be avoided, for example
M2 <- M
M2[, ] <- as.numeric(M >= thresh)
or
array(as.numeric(M >= thresh), dim=dim(M))
> One more question I have two matrices that only differ slightly. What will be the easiest way to compare and find the cells that are not the same?
If A and B are matrices of the same dimension, then
A == B
is a logical matrix with TRUE entires for positions, where
A and B match exactly.
abs(A - B) <= eps
is a logical matrix with TRUE entires for positions, where
A and B differ at most by eps.
If you want to get only one logical result, then use
all(A == B)
for exact equality and
all(abs(A - B) <= eps)
for approximate equality of all entries.
See also ?all.equal, which uses the relative error, not absolute
difference.
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list