IAMTubby
IAMTubby

Reputation: 1677

return value of which() if the condition does not find a match

Say, I have a data frame as follows

1 2
1 4
1 6
1 7
1 9

While running a loop from 1:10, I want to retrieve only those numbers which are present along with 1 in the table above, namely, 2,4,6,7,9. This is my code using the which condition, however, I get an error saying, "Error in if : argument is of length zero". I also tried with ==TRUE instead of >0, and still get the same error.

for(i in 1:10)
{
 if(which((mydata[,1] == 1) & (mydata[,2] == i)) > 0)
 {
  print("yes");
 }
 else
 {
  print("no")
 }
} 

Upvotes: 2

Views: 212

Answers (1)

flodel
flodel

Reputation: 89097

Like suggested, you would have to check the length of which's output:

if (length(which(mydata[,1] == 1 & mydata[,2] == i)) > 0)

A more appropriate tool for this is any:

if (any(mydata[,1] == 1 & mydata[,2] == i))

I also suggested removing the two sets of innermost parentheses since the == operator has higher precedence than & (see ?Syntax).

Upvotes: 4

Related Questions