条件长度> 1,仅使用第一个元素

soo*_*sus 25 conditional if-statement r calculated-columns

我有一个数据帧,旅行:

> 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 
Run Code Online (Sandbox Code Playgroud)

我想添加第三列mutType,遵循以下规则:

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"
   }
}
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

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
Run Code Online (Sandbox Code Playgroud)

我不认为我的逻辑陈述应该是生成向量,但也许我错过了一些东西.trip $ mutType 应该看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

谁能发现这里有什么问题?我需要|| 而不是| 也许?

sgi*_*ibb 42

您收到错误,因为if只能评估logical长度为1 的向量.

也许你错过了&(|)和&&(||)之间的区别.较短的版本以元素方式工作,较长的版本仅使用每个向量的第一个元素,例如:

c(TRUE, TRUE) & c(TRUE, FALSE)
# [1] TRUE FALSE

# c(TRUE, TRUE) && c(TRUE, FALSE)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

您根本不需要该if声明:

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"
Run Code Online (Sandbox Code Playgroud)