首页 > 解决方案 > 为什么第二个 ifelse 没有在 R 中评估,为什么 if else 没有矢量化?

问题描述

考虑以下内容df

structure(list(GID7173723 = c("A", "T", "G", "A", "G"), GID4878677 = c("G", 
"C", "G", "A", "G"), GID88208 = c("A", "T", "G", "A", "G"), GID346403 = c("A", 
"T", "G", "A", "G"), GID268825 = c("G", "C", "G", "A", "G")), row.names = c(NA, 
5L), class = "data.frame")

这是它的外观:

  GID7173723 GID4878677 GID88208 GID346403 GID268825
1          A          G        A         A         G
2          T          C        T         T         C
3          G          G        G         G         G
4          A          A        A         A         A
5          G          G        G         G         G

现在考虑两个向量:

ref <- c("A", "T", "G", "A", "G")
alt <- c("G", "C", "T", "C", "A")

和功能:

f = function(x){
  ifelse(x==ref,2,x)
  ifelse(x==alt,0,x)
}

当我sapply只运行第二个ifelse评估时:

sapply(dfn,f)

     GID7173723 GID4878677 GID88208 GID346403 GID268825
[1,] "A"        "0"        "A"      "A"       "0"      
[2,] "T"        "0"        "T"      "T"       "0"      
[3,] "G"        "G"        "G"      "G"       "G"      
[4,] "A"        "A"        "A"      "A"       "A"      
[5,] "G"        "G"        "G"      "G"       "G"    

如果我运行类似的东西:

f = function(x){
  if (x==ref) {return(2)
    
  }
  else if (x==alt) {return(0)
    
  }
  else {
    return(x)
  }
} 

我收到警告消息:

sapply(dfn,f)

Warning messages:
1: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
2: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
3: In if (x == alt) { :
  the condition has length > 1 and only the first element will be used
4: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
5: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
6: In if (x == ref) { :
  the condition has length > 1 and only the first element will be used
7: In if (x == alt) { :
  the condition has length > 1 and only the first element will be used

我相信后一个功能是由于if else不矢量化的性质。我真的很想解决这个问题,既不使用for循环,也不sweep使用if else语句,然后是apply族函数。

标签: rif-statementsapply

解决方案


您可以尝试在第一次调用时分配ifelse

f <- function(x){
    x <- ifelse(x == ref, 2, x)
    return(ifelse(x == alt, 0, x))
}

您当前方法的主要问题是,如果ifelse没有在 LHS 上分配任务,第一个问题就不会“坚持”。


推荐阅读