2

次のタイプのデータがあります

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
4

2 に答える 2

8
ifelse (ex1[1] == ex1[2] & ex1[1] == ex1$qit, 1,
        ifelse ( ex1[1] == ex1$qit | ex1[2] == ex1$qit, 0.5,
                 NA))
于 2012-06-06T13:49:25.663 に答える
5

You need to group the first clause as you can't have multiple options on the left or right of a comparison operator like ==. So the first clause should be A == B & B == qit.

The entire things can be done as follows:

> with(ex1, ifelse(A == B & B == qit, 1, ifelse(A == qit | B == qit, 0.5, NA)))
[1] 1.0 1.0  NA  NA 0.5 0.5

where I use with() to avoid all the messy ex1$ bits.

To add the result as a new column out, use one of the following two options:

ex1 <- transform(ex1, out = ifelse(A == B & B == qit, 1, 
                                   ifelse(A == qit | B == qit, 0.5, NA)))

ex1 <- within(ex1, out <- ifelse(A == B & B == qit, 1, 
                                 ifelse(A == qit | B == qit, 0.5, NA)))
于 2012-06-06T14:07:22.880 に答える