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

我有一个数据框,旅行:


> 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:


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 应该看起来像这样:


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

有人可以在这里发现问题吗?我需要||吗 代替| 也许?


白猪掌柜的
浏览 900回答 2
2回答

POPMUISE

之所以if会出现错误,是因为只能评估logical长度为1 的向量。也许您错过了&(|)和&&(||)之间的区别。较短的版本按元素运行,而较长的版本仅使用每个向量的第一个元素,例如:c(TRUE, TRUE) & c(TRUE, FALSE)# [1] TRUE FALSE# c(TRUE, TRUE) && c(TRUE, FALSE)[1] TRUE您根本不需要该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"

鸿蒙传说

就像sgibb所说的那样,这是一个问题,与| |无关。或||。这是解决问题的另一种方法:for (i in 1:nrow(trip)) {&nbsp; if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {&nbsp; &nbsp; trip[i, 'mutType'] <- "G:C to T:A"&nbsp; }&nbsp; else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {&nbsp; &nbsp; trip[i, 'mutType'] <- "G:C to C:G"&nbsp; }&nbsp; else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {&nbsp; &nbsp; trip[i, 'mutType'] <- "G:C to A:T"&nbsp; }&nbsp; else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {&nbsp; &nbsp; trip[i, 'mutType'] <- "A:T to T:A"&nbsp; }&nbsp; else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {&nbsp; &nbsp; trip[i, 'mutType'] <- "A:T to G:C"&nbsp; }&nbsp; else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {&nbsp; &nbsp; trip[i, 'mutType'] <- "A:T to C:G"&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP