[R] unary "-" on logicals

Robert Gentleman rgentlem at jimmy.harvard.edu
Thu Oct 11 23:53:34 CEST 2001


On Thu, Oct 11, 2001 at 03:38:02PM -0600, HEUMANN,JOHN (A-Loveland,ex1) wrote:
> "An Introduction to R" says that arithmetic operators
> coerce logical vectors to numeric vectors. This doesn't
> seem to be true for unary "-" however: 
> 
> > x <- 1:10
> > p1 <- (x > 5)
> > p2 <- (-p1)
> > is.logical(p2)
> [1] TRUE
> > is.numeric(p2)
> [1] FALSE
> 
> Since "==" always does binary comparison, this can lead to
> some bizarre behavior:
> 
> > p1
>  [1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
> > p2
>  [1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
> > (p1 == p2)
>  [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
> > ((!p1) == (!p2))
>  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

If you try 
> as.numeric(p1)
 [1] 0 0 0 0 0 1 1 1 1 1
> as.numeric(p2)
 [1]  0  0  0  0  0 -1 -1 -1 -1 -1

 So there is a coercion and a bug,
 somehow p2 is not forgetting to be a logical....


> 
> Considering that p1 and p2 are both logicals, the last two
> results seem to defy Boolean logic.
> 
> Is the fact that -p1 remains a logical instead of a numeric
> intentional or a bug? 
> 
> Regards,
> -jh-
> 
> =========================================
> John M. Heumann, Agilent Technologies
> 815 14th St. S.W., Loveland, CO 80537 USA
> Email: john_heumann at agilent.com
> Phone: 970 679-3761 FAX: 970 679-5399
> =========================================
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

-- 
+---------------------------------------------------------------------------+
| Robert Gentleman                 phone : (617) 632-5250                   |
| Associate Professor              fax:   (617)  632-2444                   |
| Department of Biostatistics      office: M1B28
| Harvard School of Public Health  email: rgentlem at jimmy.dfci.harvard.edu   |
+---------------------------------------------------------------------------+
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list