r - 为什么第二个 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
族函数。
解决方案
您可以尝试在第一次调用时分配ifelse
:
f <- function(x){
x <- ifelse(x == ref, 2, x)
return(ifelse(x == alt, 0, x))
}
您当前方法的主要问题是,如果ifelse
没有在 LHS 上分配任务,第一个问题就不会“坚持”。
推荐阅读
- javascript - 如何将对象添加到 JavaScript 中的特定位置?
- python - 构建 Python Wheel 包时如何指定构建目录?
- java - 如何在 Java 中获取时间戳为 48962-08-06T23:16:59.000Z 的 Instant 对象
- java - 输入的所有奇数位的总和
- c - 如何检测用户何时使用程序>文件?
- python - 导入特定模块不起作用-kivy apk
- c - VS 链接器找不到 PsGetProcessWow64Process
- windows - 使用带有 virtualbox 执行器的 gitlab-runner 确定 vagrant 的 CI/CD 管道的正确方法?
- c# - 计算四面体外心的问题
- flutter - 键盘溢出 * 像素。无法使用 SingleChildScrollView 或 ListView