2
我有以下類型的數據條件ifelse r中
ex1 <- data.frame (A = 1:6, B = c(1,2,3,5,1,1), qit = c(1,2,1,2,5,1))
ex1
A B qit
1 1 1 1
2 2 2 2
3 3 3 1
4 4 5 2
5 5 1 5
6 6 1 1
的我嘗試以下ifelse循環,但不是佔有我需要..
ifelse (ex1[1] == ex1[2] & ex1$qit, 1,
ifelse (ex1[1]== ex1$qit || ex1[2]== ex1$qit, 0.5,
NA))
條件是:
(1) If A = B = qit , then output 1 (else)
(2) Either A = qit or B = qit then output = 0.5 (else)
(3) If none of above conditions hold output NA
我認爲我有使用&的問題,但我試過ex1 [1] == ex1 [2] == ex1 $ qit給出錯誤。
預期輸出:
ex1$out <- c(1, 1, NA, NA, 0.5, 0.5)
A B qit out
1 1 1 1 1.0
2 2 2 2 1.0
3 3 3 1 NA
4 4 5 2 NA
5 5 1 5 0.5
6 6 1 1 0.5
闡釋瞭解決方案:
Soultion for the first row:
A = B = qit all conditions hold true so the output 1
For second row
A = B = qit all conditions hold true so the output 1
For third row
A = B but not equal to qit output NA
For fourth row
A is not equal to B nor equal to qit output NA
Fifth row
A = qit (however A = B = qit doesnot hold true) so output 0.5
Sixth row
B = qit (however A = B = qit doesnot hold true) so output 0.5