2012-06-06 5 views
2

I ont le type de données suivantesconditions dans ifelse en 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 

J'ai essayé la boucle suivante ifelse mais pas geting ce que je dois ..

ifelse (ex1[1] == ex1[2] & ex1$qit, 1, 
     ifelse (ex1[1]== ex1$qit || ex1[2]== ex1$qit, 0.5, 
      NA)) 

Condition est:

(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 

Je pense que j'ai un problème avec l'utilisation de &, mais j'ai essayé ex1 [1] == ex1 [2] == ex1 $ qit donne une erreur.

Résultats attendus:

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 

Explication à la solution:

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 

Répondre

8
ifelse (ex1[1] == ex1[2] & ex1[1] == ex1$qit, 1, 
     ifelse (ex1[1] == ex1$qit | ex1[2] == ex1$qit, 0.5, 
       NA)) 
5

Vous devez regrouper la première clause que vous ne pouvez pas avoir plusieurs options à gauche ou à droite un opérateur de comparaison comme ==. Donc, la première clause devrait être A == B & B == qit.

Les choses entières peut se faire comme suit:

> 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 

où j'utilise with() pour éviter tous les ex1$ en désordre morceaux.

Pour ajouter le résultat comme une nouvelle colonne out, utilisez l'une des deux options suivantes:

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))) 
Questions connexes