[R] if statement problem

Rui Barradas ruipbarradas at sapo.pt
Sun Dec 25 21:22:20 CET 2011


Hello again.

I don't understand what didn't work.

First, it seems better to use 'nrow', the result is the same

 stopifnot(length(x[,1]) == nrow(x))

Then your multiple  OR condition.

#if((x[i,1] || x[i,2] || x[i,3] || x[i,4]) < 5)

x <- matrix(1:24, ncol=4)

for(i in 1:nrow(x))
	if(any(x[i,] < 5))
		cat("At least one is TRUE:", i, "\n")

for(i in 1:nrow(x))
	if((x[i,1] < 5) | (x[i,2] < 5) | (x[i,3] < 5) | (x[i,4] < 5))
		cat("The same with '|':", i, "\n")

In the second example each condition IS a condition. Unlike your original
"compound" one.
The 'Introduction to R' clearly states '|' as the union of the logical
expressions, The section is 2.4.
Also read Patrick's PDF, the parts I've read are great and very usefull.

(Thanks, Patrick, I was unaware of R inferno.pdf)

As a side note, you are duplicating the matrix 'a' assignement. Why not just
before the 'if'?
Then, you could simply test if any 'a' is less than 5.

for (i in 1: row(x))
{
           a[1,1]  <- x[i,1];
           a[1,2] <- x[i,2];
           a[2,1] <- x[i,3];
           a[2,2] <- x[i,4];
           if(any(a < 5))
             {
                    etc...
   
(Or use the compound '|' ).

Rui Barradas

--
View this message in context: http://r.789695.n4.nabble.com/if-statement-problem-tp4230026p4233312.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list