[R] conditional assignment

Roger Bivand Roger.Bivand at nhh.no
Mon Jan 26 20:36:05 CET 2004


On Mon, 26 Jan 2004 uaca at alumni.uv.es wrote:

> 
> Hi all
> 
> 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) ?????
> 

Break it down into bits:

> z<- c(1, 2, 3)
> (z > 2)
[1] FALSE FALSE  TRUE
> ( zz <- z)
[1] 1 2 3
> (z > 2) & ( zz <- z)
[1] FALSE FALSE  TRUE
> TRUE & ( zz <- z)
[1] TRUE TRUE TRUE
> rep(TRUE,4) & ( zz <- z)
[1] TRUE TRUE TRUE TRUE
Warning message: 
longer object length
        is not a multiple of shorter object length in: rep(TRUE, 4) & (zz <- z) 

The first part is a logical vector, the second is the result of assigning 
z to zz, & of them isn't terribly meaningful?

Try:

> zz <- ifelse(z > 2, z, 0)
> zz
[1] 0 0 3

if that's what you want.

> 
> the null <- assignment is to keep the console silent
> 
> in the other hand, it curious that null has reasonable values
> 
> > null
> [1] FALSE FALSE  TRUE
> 
> Thanks in advance
> 
> 	Ulisses
> 
>                 Debian GNU/Linux: a dream come true
> -----------------------------------------------------------------------------
> "Computers are useless. They can only give answers."            Pablo Picasso
> 
> Humans are slow, innaccurate, and brilliant.
> Computers are fast, acurrate, and dumb. 
> Together they are unbeatable
> 
> --->	Visita http://www.valux.org/ para saber acerca de la	<---
> --->	Asociación Valenciana de Usuarios de Linux		<---
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> 

-- 
Roger Bivand
Econonic Geography Section, Department of Economics, Norwegian School of 
Economics and Business Administration, Breiviksveien 40, N-5045 Bergen, 
Norway, voice: +47-55959355, fax: +47-55959393; Roger.Bivand at nhh.no




More information about the R-help mailing list