[R] conditional assignment
Prof Brian Ripley
ripley at stats.ox.ac.uk
Mon Jan 26 21:34:46 CET 2004
On Mon, 26 Jan 2004, Simon Cullen wrote:
> 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)
assignment returns the new value of zz, which as it is all non-zero
coerces to the logical vector T T T
> =(F F T).
>
> What will work is:
> z <- c(1, 2, 3)
> index <- z>2
> zz <- z * index
Rather better I think is
zz <- ifelse(z > 2, z, zz)
or even
ind <- z > 2
zz[ind] <- z[ind]
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list