简体   繁体   English

R中的ifelse语句

[英]ifelse statement in R

I'm looking at a gene in 10 people. 我正在寻找10个人中的一个基因。 And this gene has two alleles, say a and b . 这个基因有两个等位基因,例如ab And each allele has 3 forms: type 2, 3 or 4. 每个等位基因有3种形式:2型,3型或4型。

a <- c(2, 2, 2, 2, 3, 3, 3, 2, 4, 3)
b <- c(4, 2, 3, 2, 4, 2, 3, 4, 4, 4)

I wish to code a variable that tells me how many type 4 alleles the person has: 0, 1, or 2. 我希望编写一个变量,告诉我该人有多少个4类等位基因:0、1或2。

var <- ifelse(a==4 & b==4, 2, 0)

The code above doesn't work since I didn't account for the individuals who have just one copy of the type 4 allele. 上面的代码不起作用,因为我没有考虑只有一个4型等位基因副本的个体。 I feel like I might need 2 ifelse statements that work simultaneously? 我觉得我可能需要2个同时工作的ifelse语句?

EDIT: You don't actually need ifelse or any fancy operations other than plus and equal to. 编辑:您实际上不需要ifelse或加号和等于号以外的任何花式操作。

var <- (a == 4) + (b == 4)

If you're set on ifelse , this can be done with 如果您设置为ifelse ,则可以使用

var <- ifelse(a == 4, 1, 0) + ifelse(b == 4, 1, 0)

However, I prefer the following solution using apply . 但是,我更喜欢以下使用apply解决方案。 The following will give you three cases, the result being the number of 4's the person has (assuming each row is a person). 以下将给您三种情况,结果是此人拥有的4的数量(假设每一行都是一个人)。

a = c(2, 2, 2, 2, 3, 3, 3, 2, 4, 3)
b = c(4, 2, 3, 2, 4, 2, 3, 4, 4, 4)

d <- cbind(a,b)

apply(d, 1, function(x) {sum(x == 4)})

For this operation, I first combined the two vectors into a matrix since it makes applying the function easier. 对于此操作,我首先将两个向量合并到一个矩阵中,因为这使应用该函数更加容易。 In R, generally if data are the same type it is easier (and faster for the computer) to combine the data into a matrix/data frame/etc., then create a function to be performed on each row/column/etc. 在R中,通常,如果数据是相同类型,则将数据组合成矩阵/数据框/等时比较容易(对于计算机而言更快),然后创建要在每行/列/等上执行的功能。

To understand the output, consider what happens to the first row of d. 要了解输出,请考虑d的第一行会发生什么。

> d[1, ]
a b 
2 4

> d[1, ] == 4
a     b 
FALSE  TRUE

Booleans are interpreted as integers under addition, so 布尔值在加法运算中被解释为整数,因此

> FALSE + TRUE
[1] 1

It doesn't seem to matter whether the 4 came from a or b, so we end up with three cases: 0, 1, and 2, depending on the number of 4's. 看起来4是来自a还是b似乎都没有关系,所以我们最终得出三种情况:0、1和2,具体取决于4的数目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM