Simple if-else loop in R

Can someone tell me what is wrong with this if-else loop in R? I often cannot get if-else loops to work. I get an error message:

if(match('SubjResponse',names(data))==NA) { observed <- data$SubjResponse1 } else { observed <- data$SubjResponse } 

Note that data is a data frame.

Mistake

 Error in if (match("SubjResponse", names(data)) == NA) { : missing value where TRUE/FALSE needed 
+8
r if-statement
source share
2 answers

As @DirkEddelbuettel pointed out, you cannot test NA this way. But you can do match not return NA :

Using nomatch=0 and changing the if clause (since 0 considered FALSE ), the code can be simplified. In addition, another useful coding idiom is to assign the result of an if clause so you will not mistakenly enter a variable name in one of the branches ...

So, I will write like this:

 observed <- if(match('SubjResponse',names(data), nomatch=0)) { data$SubjResponse # match found } else { data$SubjResponse1 # no match found } 

By the way, if you have "often" problems with if-else, you should know about two things:

  • The object for testing should not contain NA or NaN or be a string (mode symbol) or another type that cannot be forced into a logical value. Numeric: 0 is FALSE anything else (but NA / NaN) TRUE .

  • The length of the object must be exactly 1 (scalar value). It may be more, but then you will get a warning. If it is shorter, you will receive an error message.

Examples:

 len3 <- 1:3 if(len3) 'foo' # WARNING: the condition has length > 1 and only the first element will be used len0 <- numeric(0) if(len0) 'foo' # ERROR: argument is of length zero badVec1 <- NA if(badVec1) 'foo' # ERROR: missing value where TRUE/FALSE needed badVec2 <- 'Hello' if(badVec2) 'foo' # ERROR: argument is not interpretable as logical 
+2
source share

This is not a complete example, since we have no data, but I see the following problems:

  • You cannot verify NA with == , you need is.na()
  • Similarly, the output of match() and friends is usually tested for NULL or length()==0
  • I try to write } else { on one line.
+7
source share

All Articles