[S] if with vector antecedent and vector consequent

Psychology (conjoint@u.washington.edu)
Sun, 2 Aug 1998 00:06:40 -0700 (PDT)

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

cbind(x,y) yield:
x y
[1,] 1 2
[2,] 2 2
[3,] 3 2
[4,] 4 1
[5,] 5 1
[6,] 6 1

I want to replace the for loop with a function, call
it "vector.if", that would let me write

vector.if (x < 4) y <- y + 1

Of course, I can write such a function with a for loop as part
of its definition. I'm wondering whether there is an elegant
way to do without the for loop altogether.

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