[R] if ... problem with compound instructions

Bill.Venables at csiro.au Bill.Venables at csiro.au
Mon Jan 1 07:09:24 CET 2007

Step 1:

quadrant <- 1 + (X[, 1] < 0) + 2*(X[, 2] > 0)

This is not the usual labelling of the quadrants as '3' and '4' are interchanged. If you want to be picky about it

quadrant <- ifelse(quadrant > 2, 7 - quadrant, quadrant)

Step 2:

angle <- atan2(X[,2], X[,1]) %% (2*pi)  # I think this is what you want

(why did you want to know the quadrant?)

Oh, then you might do

X[, 3:4] <- cbind(quadrant, angle)


Bill Venables
CMIS, CSIRO Laboratories,
PO Box 120, Cleveland, Qld. 4163
Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):    +61 7 3826 7304
Mobile (rarely used):                +61 4 1963 4642
Home Phone:                          +61 7 3286 7700
mailto:Bill.Venables at csiro.au

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Richard Rowe
Sent: Monday, 1 January 2007 12:36 PM
To: r-help at stat.math.ethz.ch
Subject: [R] if ... problem with compound instructions

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
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 
assigning quadrant and calculating heading

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 (

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 ?


Richard Rowe

Dr Richard Rowe
Zoology & Tropical Ecology
School of Tropical Biology
James Cook University
Townsville 4811

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
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list