[R] conditional assignment

Liaw, Andy andy_liaw at merck.com
Mon Jan 26 21:10:44 CET 2004


> From: Simon Cullen
> On Mon, 26 Jan 2004 20:15:51 +0100, <uaca at alumni.uv.es> wrote:
> 
> > I want to conditionally operate on certain elements of a 
> matrix, let me
> > explain it with a simple vector example
> >
> >
> >> z<- c(1, 2, 3)
> >> zz <- c(0,0,0)
> >> null <- (z > 2) & ( zz <- z)
> >> zz
> > [1] 1 2 3
> >
> > why zz is not (0, 0, 3) ?????
> <snip>
> >
> > in the other hand, it curious that null has reasonable values
> >
> >> null
> > [1] FALSE FALSE  TRUE
> 
> What you have done there is create a boolean vector, null, of 
> the same  
> length as z (and zz).
> 
> For instance:
> (z > 2) & (zz <- z)
> =(F F T) & (T T T) (as assignment - presumably - returns T)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Don't think so.  zz <- z has the value z; i.e., c(1, 2, 3).  When evaluated
as logicals, non-zero values are treated as true (as in C), I believe.  For
example:

> z <- rep(0, 3)
> ifelse(zz <- z, 1, 0)
[1] 0 0 0
>  (zz <- z) == TRUE
[1] FALSE FALSE FALSE

However, what tripped me is the fact that even though non-zero is logically
`true', it's not necessarily equal to TRUE (which is numerically equal to
1):

> z <- 0:2
>  (zz <- z) == TRUE
[1] FALSE  TRUE FALSE
> ifelse(zz <- z, 1, 0)
[1] 0 1 1
> if(3) TRUE else FALSE
[1] TRUE

Andy




> =(F F T).
> 
> What will work is:
> z <- c(1, 2, 3)
> index <- z>2
> zz <- z * index
> 
> 
> -- 
> SC
> 
> Simon Cullen
> Room 3030
> Dept. Of Economics
> Trinity College Dublin
> 
> Ph. (608)3477
> Email cullens at tcd.ie


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list