[R] dimension-preserving matrix coersion

William Dunlap wdunlap at tibco.com
Mon Sep 28 01:25:05 CEST 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Murat Tasan
> Sent: Sunday, September 27, 2009 3:59 PM
> To: r-help at r-project.org
> Subject: [R] dimension-preserving matrix coersion
> 
> i've written a function to coerce a matrix (e.g. from numeric to
> logical), but i'd like to know if someone has a more elegant method
> for this:
> 
> > m <- matrix(c(0, 1, 1, 0), ncol = 2)
> > m <- as.logical(m)
> > m
> [1] FALSE TRUE TRUE FALSE
> 
> i'd like 'm' to still be a matrix with the original dimensions.  in my
> function to do this, i coerce 'm' to a logical, then re-form it as a
> matrix, which seems like an extra (possibly bug-introducing) step that
> might be avoided if i knew of some "hidden" feature that might permit
> this in one fell swoop.

  m <- m != 0
will do it, as will
  mode(m) <- "logical"

The former has the advantage that you don't have to use the
canonical mapping of 0<->FALSE,anything else<->TRUE, but
can use any standard comparison or vectorized logical operator.
It also seems cleaner in that it can be used inside a larger expression,
like m[m!=0].

Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com  

> 
> any ideas?
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 




More information about the R-help mailing list