[英]Simple if-else loop in R
有人能告訴我這個在R中的if-else循環有什么問題嗎? 我經常無法使if-else循環工作。 我收到一個錯誤:
if(match('SubjResponse',names(data))==NA) {
observed <- data$SubjResponse1
}
else {
observed <- data$SubjResponse
}
請注意, data
是數據框。
錯誤是
Error in if (match("SubjResponse", names(data)) == NA) { :
missing value where TRUE/FALSE needed
這不是一個完整的例子,因為我們沒有數據,但我看到了這些問題:
==
測試NA
,你需要is.na()
match()
和friends的輸出通常測試為NULL或length()==0
} else {
正如@DirkEddelbuettel指出的那樣,你不能用那種方式測試NA
。 但你可以讓match
不返回NA
:
通過使用nomatch=0
並反轉if
子句(因為0
被視為FALSE
),代碼可以簡化。 此外,另一個有用的編碼習慣是分配if子句的結果,這樣你就不會錯誤地在其中一個分支中輸入變量名...
所以我會這樣寫:
observed <- if(match('SubjResponse',names(data), nomatch=0)) {
data$SubjResponse # match found
} else {
data$SubjResponse1 # no match found
}
順便說一句,如果你“經常”遇到if-else問題,你應該注意兩件事:
要測試的對象不得包含NA或NaN,或者是字符串(模式字符)或其他無法強制轉換為邏輯值的類型。 數字正常:0為FALSE
其他任何東西(但NA / NaN)為TRUE
。
對象的長度應該是1(標量值)。 它可能會更長,但隨后會收到警告。 如果它更短,則會出錯。
例子:
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.