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
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'
Tommy
source share