我想在 a 中創建一個data.table帶有一些嵌套ifelse()陳述句的新列:我在最后包含了一個控制元件stop(),它永遠不應該達到。在我的示例中,要么condition_a或condition_b必須是"Y". stop()永遠不應該達到,但確實如此。誰可以給我解釋一下這個?
示例代碼:
library(data.table)
condition_a <- c("Y", "Y", "Y", "Y", "Y", "Y")
condition_b <- c("Y", "Y", "Y", "Y", "Y", "N")
dt <- data.table(condition_a, condition_b)
dt <-
dt[, conditions := ifelse(test = ((condition_a == "Y") &
(condition_b == "Y")),
yes = "a_and_b",
no = ifelse(test = ((condition_a == "N") &
(condition_b == "Y")),
yes = "b",
no = ifelse(test = ((condition_a == "Y") &
(condition_b == "N")),
yes = "a",
no = ifelse(test = ((condition_a == "N") &
(condition_b == "N")),
yes = stop('double "N" found'),
no = stop("this should not happen")))))]
謝謝你的幫助 :)。
uj5u.com熱心網友回復:
您獲得了一個錯誤,因為ifelse經常評估它的所有引數(但并非總是如此:有些情況下沒有像 in 一樣的評估ifelse(test=c(1, NA)==c(NA, 1), stop("notEval"), stop("notEavl"));請注意,在這種特殊情況下,test引數的計算結果僅為NAs)。
如果您只想在必要時評估引數,您應該使用 data.table 函式fcase,它是嵌套 ifelse 的一個很好且智能的實作。
dt[, conditions := fcase(condition_a == "Y" & condition_b == "Y", "a_and_b",
condition_a == "N" & condition_b == "Y", "b",
condition_a == "Y" & condition_b == "N", "a",
condition_a == "N" & condition_b == "N", stop('double "N" found'))]
在這種情況下,陳述句 withstop將永遠不會被評估,因為沒有 wherecondition_a == "N" & condition_b == "N"評估為TRUEin 的情況dt。
另請注意, data.table 通過參考起作用;因此,使用時無需重新分配您的 data.table :=。也就是說,dt[, conditions := ...]將向dt. 您不需要<-像 in 那樣使用賦值運算子dt <- dt[, conditions := ...]。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524339.html
上一篇:程式沒有給出期望的輸出
下一篇:Livesql觸發IF陳述句
