R中的简单if-else循环 [英] Simple if-else loop in R

查看:536
本文介绍了R中的简单if-else循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我在R中这个if-else循环有什么问题吗?我经常无法让if-else循环工作。我收到错误:

Can someone tell me what is wrong with this if-else loop in R? I frequently can't get if-else loops to work. I get an error:

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

请注意数据是一个数据框。

错误是

Error in if (match("SubjResponse", names(data)) == NA) { : 
  missing value where TRUE/FALSE needed


推荐答案

As @ DirkEddelbuettel指出,你不能用这种方式测试 NA 。但你可以匹配不返回 NA

As @DirkEddelbuettel noted, you can't test NA that way. But you can make match not return NA:

通过使用 nomatch = 0 并反转 if 子句(因为 0 被视为 FALSE ),代码可以简化。此外,另一个有用的编码习惯是分配if子句的结果,这样你就不会在其中一个分支中输错变量名...

By using nomatch=0 and reversing the if clause (since 0 is treated as FALSE), the code can be simplified. 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...

所以我这样写:

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

顺便说一句,如果你经常遇到if-else问题,你应该知道两件事:

By the way if you "frequently" have problems with if-else, you should be aware of two things:


  1. 要测试的对象不得包含NA或NaN,或者是字符串(模式字符)或其他无法强制转换为逻辑值的类型。数字正常:0 FALSE 其他任何东西(但NA / NaN) TRUE

  1. 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. Numeric is OK: 0 is FALSE anything else (but NA/NaN) is TRUE.

对象的长度应该是1(标量值)。 可以更长,但随后会收到警告。如果它更短,则会出错。

The length of the object should be exactly 1 (a scalar value). It can be longer, but then you get a warning. If it is shorter, you get an error.

示例:

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

这篇关于R中的简单if-else循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆