[英]Simple if-else loop in R
Can someone tell me what is wrong with this if-else loop in R? 有人能告诉我这个在R中的if-else循环有什么问题吗? I frequently can't get if-else loops to work.
我经常无法使if-else循环工作。 I get an error:
我收到一个错误:
if(match('SubjResponse',names(data))==NA) {
observed <- data$SubjResponse1
}
else {
observed <- data$SubjResponse
}
Note that data
is a data frame. 请注意,
data
是数据框。
The error is 错误是
Error in if (match("SubjResponse", names(data)) == NA) { :
missing value where TRUE/FALSE needed
This is not a full example as we do not have the data but I see these issues: 这不是一个完整的例子,因为我们没有数据,但我看到了这些问题:
NA
with ==
, you need is.na()
==
测试NA
,你需要is.na()
match()
and friends is usually tested for NULL or length()==0
match()
和friends的输出通常测试为NULL或length()==0
} else {
on one line. } else {
As @DirkEddelbuettel noted, you can't test NA
that way. 正如@DirkEddelbuettel指出的那样,你不能用那种方式测试
NA
。 But you can make match
not return NA
: 但你可以让
match
不返回NA
:
By using nomatch=0
and reversing the if
clause (since 0
is treated as FALSE
), the code can be simplified. 通过使用
nomatch=0
并反转if
子句(因为0
被视为FALSE
),代码可以简化。 Furthermore, another useful coding idiom is to assign the result of the if clause, that way you won't mistype the variable name in one of the branches... 此外,另一个有用的编码习惯是分配if子句的结果,这样你就不会错误地在其中一个分支中输入变量名...
So I'd write it 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 "frequently" have problems with if-else, you should be aware of two things: 顺便说一句,如果你“经常”遇到if-else问题,你应该注意两件事:
The object to test must not contain NA or NaN, or be a string (mode character) or some other type that can't be coerced into a logical value. 要测试的对象不得包含NA或NaN,或者是字符串(模式字符)或其他无法强制转换为逻辑值的类型。 Numeric is OK: 0 is
FALSE
anything else (but NA/NaN) is TRUE
. 数字正常:0为
FALSE
其他任何东西(但NA / NaN)为TRUE
。
The length of the object should be exactly 1 (a scalar value). 对象的长度应该是1(标量值)。 It can be longer, but then you get a warning.
它可能会更长,但随后会收到警告。 If it is shorter, you get an error.
如果它更短,则会出错。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.