[R] if ... problem with compound instructions
richard.rowe at jcu.edu.au
Mon Jan 1 03:35:41 CET 2007
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 ?
Dr Richard Rowe
Zoology & Tropical Ecology
School of Tropical Biology
James Cook University
ph +61 7 47 81 4851
fax +61 7 47 25 1570
JCU has CRICOS Provider Code 00117J
More information about the R-help