[R] if ... problem with compound instructions

From: Richard Rowe <richard.rowe_at_jcu.edu.au>
Date: Mon 01 Jan 2007 - 02:35:41 GMT

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
AUSTRALIA ph +61 7 47 81 4851
fax +61 7 47 25 1570
JCU has CRICOS Provider Code 00117J

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon Jan 01 13:41:50 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 01 Jan 2007 - 15:30:23 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.