【问题标题】:Why does for loop not iterate with (i in 1:1523)?为什么 for 循环不使用 (i in 1:1523) 进行迭代?
【发布时间】:2016-02-24 20:15:02
【问题描述】:

我的 for 循环出现错误。代码如下:

#finding IDs with >5% replicate variance
#initialize vectors
LS1repvariance = NULL 
anomalylist = NULL

#open for loop iterating from 1 to end of dataset
for (i in 1:1523){ 
  #call replicates, which start off as characters
  charrep1 = widesubdat[i,2] 
  charrep2 = widesubdat[i,11]

  #convert to numeric 
  rep1 = as.numeric(charrep1) 
  rep2 = as.numeric(charrep2) 

  #calculation
  repvariance = (rep1-rep2)/((rep1+rep2)/2)*100 

  #if loop for anomalous replicates
  if (abs(repvariance)>=5) 
    anomalylist[i]=widesubdat[i,0] 
  }

我得到的错误说

if (abs(repvariance) >= 5) anomalylist[i] = widesubdat[i, 0] 中的错误 : 需要 TRUE/FALSE 的缺失值

我认为错误出在迭代中,因为它将 i 定义为 336L,并且它没有正确调用 charrep,但我不知道为什么。我已经在 python 中完成了 for 循环,但从未在 R 中完成过,但所有 for 循环帮助页面似乎都具有相同的结构。我可以在 for 循环之外运行的所有行都可以测试。

我读过 if 语句也需要大括号,但是当我使用它们时,IDLE 说意外的“{”。

【问题讨论】:

  • widesubdat[i,0] 不正确。 R 从 1 开始索引,而不是 0。
  • 这不会产生错误。您可能在 repvariance 中有一个 NA 值导致该错误。 if(NA) 1 else 1.

标签: r for-loop iteration


【解决方案1】:

你也可以放弃循环

pick <- abs(200*(widesubdat[,2]-widesubdat[,11])/(widesubdat[,2]+widesubdat[,11]))>=5
anomalylist <- widesubdat[,1]  # Note the comment above with index 0
anomalylist[!pick] <- NA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2016-01-18
    • 2014-08-09
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多