# [R] if ... problem with compound instructions

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jan 1 03:52:07 CET 2007

```On 12/31/2006 9:35 PM, Richard Rowe wrote:
> I am having problems with the 'if' syntax.
>
> I have an n x 4 matrix, X say.  The first two columns hold x, y values and
> I am attempting to fill the second two columns with the quadrant in which
> the datapoint (x, y) is and with the heading angle.
>
> So I have two problems
> 1) how to do this elegantly (at which I've failed as I can't seem to
> vectorize the problem) and

You would use the ifelse() function for a vectorized solution.

> 2) how to accomplish the task in a for loop ...
>
> for (i in 1: length(X[,1])) (
>   if ((X[i,1] ==0) & (X[i,2] ==0)) (X[i,3] <- NA; X[i,4] <-NA) else (
> removing the pathological case ... then a series of nested if statements
>
> e.g.
> if ((X[i,1] < 0) & (X[i,2] >= 0)) (X[i,3] <- 4; X[i,4] <-
> atan(X[i,1]/X[i,2]) + 2*pi) else (

Use {} rather than () around blocks of statements, and &&
rather than & for most logical constructions, e.g.

if ((X[i,1] < 0) && (X[i,2] >= 0)) {
X[i,3] <- 4; X[i,4] <- atan(X[i,1]/X[i,2]) + 2*pi
} else {

...

Duncan Murdoch

>
>
> In the first instance the ';'  seems to the source of a syntax
> error.  Removing the second elements of the compound statement solves the
> syntax problem and the code runs.
>
> As the R syntax is supposed to be 'Algol-like' I had thought
>
> if <A> then <B> else <C>
> should work for compound <B> ... ie that the bracket (X[i,3] <- NA; X[i,4]
> <-NA) should be actioned
>
> 1) any elegant solutions to what must be a common task?
>
> 2) any explanations for the ';' effect ?
>
> thanks
>
> Richard Rowe
>
> Dr Richard Rowe
> Zoology & Tropical Ecology
> School of Tropical Biology
> James Cook University
> Townsville 4811
> AUSTRALIA
>
> ph +61 7 47 81 4851
> fax +61 7 47 25 1570
> JCU has CRICOS Provider Code 00117J
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help