【问题标题】:conditions in ifelse in rifelse 在 r 中的条件
【发布时间】:2012-06-06 13:38:55
【问题描述】:

我有以下类型的数据

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

【问题讨论】:

    标签: r loops if-statement


    【解决方案1】:
    ifelse (ex1[1] == ex1[2] & ex1[1] == ex1$qit, 1,
            ifelse ( ex1[1] == ex1$qit | ex1[2] == ex1$qit, 0.5,
                     NA))
    

    【讨论】:

      【解决方案2】:

      您需要对第一个子句进行分组,因为您不能在== 等比较运算符的左侧或右侧有多个选项。所以第一个子句应该是A == B &amp; B == qit

      整个事情可以做如下:

      > 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
      

      我使用with() 来避免所有混乱的ex1$ 位。

      要将结果添加为新列out,请使用以下两个选项之一:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-05
        • 1970-01-01
        相关资源
        最近更新 更多