[S] Summary: if with vector antecedent and vector consequent

Psychology (conjoint@u.washington.edu)
Sun, 2 Aug 1998 10:20:05 -0700 (PDT)

Original question:
> Suppose X and Y are two numeric vectors of equal length.
> I want to apply a function to the i-th value of Y if and
> only if the i-th value of X satisfies a condition. Is there
> a simple way to do this?
> I can accomplish my task with a for loop: for example:
> x <- c(1,2,3,4,5,6)
> y <- c(1,1,1,1,1,1)
> for (i in 1:6) if (x[i] < 4) y[i] <- y[i] + 1

Evidently I was missing the obvious. As several people pointed out
(Bill Venables, Muhammad Jalaluddin, Brian Ripley, Kevin Brand, ...),

y[ x < 4 ] <- y[ x < 4 ] + 1

does the trick. I must be suffering from a brain lock because I had
thought about this issue quite a bit before posting the question.
Some people have asked why I have this silly name, "Psychology", on my
address. The email account from which I access the snews list is shared
by me with several research assistants. It belongs to the psychology
department and I don't have control over the name.

John Miyamoto, Department of Psychology, Box 351525
University of Washington, Seattle, WA 98195

This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news