条件具有长度 >1 并且只使用第一个元素 [英] The condition has length > 1 and only the first element will be used
问题描述
我有一个数据框,旅行:
I have a dataframe, trip:
> head(trip.mutations)
Ref.y Variant.y
1 T C
2 G C
3 A C
4 T C
5 C A
6 G A
我想添加第三列 mutType,它遵循以下规则:
I want to add a third column, mutType, that follows these rules:
for (i in 1:nrow(trip)) {
if(trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A') {
trip[i, 'mutType'] <- "G:C to T:A"
}
else if(trip$Ref.y=='G' & trip$Variant.y=='C'|trip$Ref.y=='C' & trip$Variant.y=='G') {
trip[i, 'mutType'] <- "G:C to C:G"
}
else if(trip$Ref.y=='G' & trip$Variant.y=='A'|trip$Ref.y=='C' & trip$Variant.y=='T') {
trip[i, 'mutType'] <- "G:C to A:T"
}
else if(trip$Ref.y=='A' & trip$Variant.y=='T'|trip$Ref.y=='T' & trip$Variant.y=='A') {
trip[i, 'mutType'] <- "A:T to T:A"
}
else if(trip$Ref.y=='A' & trip$Variant.y=='G'|trip$Ref.y=='T' & trip$Variant.y=='C') {
trip[i, 'mutType'] <- "A:T to G:C"
}
else if(trip$Ref.y=='A' & trip$Variant.y=='C'|trip$Ref.y=='T' & trip$Variant.y=='G') {
trip[i, 'mutType'] <- "A:T to C:G"
}
}
但我收到错误:
Warning messages:
1: In if (trip$Ref.y == "G" & trip$Variant.y == "T" | trip$Ref.y == ... :
the condition has length > 1 and only the first element will be used
我认为我的逻辑陈述不应该产生向量,但也许我遗漏了一些东西.trip$mutType应该看起来像这样:
I don't think my logical statements should be producing vectors, but maybe I'm missing something. trip$mutType should end up looking like this:
mutType
A:T to G:C
G:C to C:G
A:T to C:G
A:T to G:C
G:C to T:A
G:C to A:T
有人能发现这里有什么问题吗?我需要吗||而不是 |也许?
Can anyone spot what's wrong here? Do I need || instead of | perhaps?
推荐答案
你得到这个错误,因为 if
只能计算长度为 1 的 logical
向量.
You get the error because if
can only evaluate a logical
vector of length 1.
也许你错过了 &
(|
) 和 &&
(||
).较短的版本按元素工作,较长的版本仅使用每个向量的第一个元素,例如:
Maybe you miss the difference between &
(|
) and &&
(||
). The shorter version works element-wise and the longer version uses only the first element of each vector, e.g.:
c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE
# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
您根本不需要 if
语句:
You don't need the if
statement at all:
mut1 <- trip$Ref.y=='G' & trip$Variant.y=='T'|trip$Ref.y=='C' & trip$Variant.y=='A'
trip[mut1, "mutType"] <- "G:C to T:A"
这篇关于条件具有长度 >1 并且只使用第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!