[英]conditions in ifelse in r
I have the following type of data 我有以下类型的数据
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
I tried the following ifelse loop but not geting what I need to .. 我尝试了以下ifelse循环,但没有尝试我需要的东西..
ifelse (ex1[1] == ex1[2] & ex1$qit, 1,
ifelse ( ex1[1]== ex1$qit || ex1[2]== ex1$qit, 0.5,
NA))
Condition is: 条件是:
(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
I think I have issue with use of &, but I tried ex1[1] == ex1[2] == ex1$qit gives an error. 我想我有使用&的问题,但我试过ex1 [1] == ex1 [2] == ex1 $ qit给出错误。
Expected output: 预期产量:
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
Explanation to the 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
ifelse (ex1[1] == ex1[2] & ex1[1] == ex1$qit, 1,
ifelse ( ex1[1] == ex1$qit | ex1[2] == ex1$qit, 0.5,
NA))
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
. 所以第一个子句应该是
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. 我用
with()
来避免所有凌乱的ex1$
位。
To add the result as a new column out
, use one of the following two options: 要添加结果作为新列
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.