Reputation: 151
I'm running a greater than test (see below) in a for loop:
if(x > y){...}
but at one point y will become numeric(0) while x will still be a numeric. So I need to know if there is a way to still test if a number is greater than numeric(0). This is the error message I get when I do it:
Error in if (x > y) { :
argument is of length zero
Is there a way to test it or even a way to substitute just plain 0 for numeric(0) in this case?
Thanks
Upvotes: 2
Views: 1512
Reputation: 664
If x
and y
are always scalars or numeric(0)
, and if numeric(0)
is equivalent to 0 in your problem, then you can write
if(sum(x) > sum(y)){...}
or leaving x
without the sum
if you know it can never become numeric(0)
.
This works because sum(numeric(0))
gives 0
.
I haven't tested whether this is faster than implementing an if
that checks the length
of y
, but I believe it should be faster (and more concise).
Upvotes: 0
Reputation: 21502
Another approach, depending (as BigFinger wrote) on what you want the branching to be,
if(length(x)>0 && x>y ) {do_your_stuff}
I am assuming here that your x
and y
are scalars. Otherwise, you'll need to be a lot more careful, as if
doesn't accept a multiple-valued outcome.
Upvotes: 1
Reputation: 1043
What is supposed to happen when you compare a number with an empty value? Should the condition x > y evaluate to TRUE or FALSE, or should there be a different effect? One way to handle the situation is like this:
if (length(y) == 0) {
cat("y is numeric(0)")
} else {
if (x > y) {
cat("x is greater than y")
} else {
cat("x is less than or equal y")
}
}
Upvotes: 1