【问题标题】:Is there a way to add the number of outputs from a for loop in R?有没有办法在 R 中添加 for 循环的输出数量?
【发布时间】:2019-12-09 05:50:27
【问题描述】:

我插入了一个 for 循环:

for(j in 2:1036) {
  nMatchingLoci = 0
  for(i in 1:1) {
    if(sampGeno[1,i]==FGMMdata[1,i,j] && sampGeno[2,i]==FGMMdata[2,i,j]) {
      nMatchingLoci = nMatchingLoci + 1
    }
  }

  if(nMatchingLoci==1) {
    print(paste("!!! 1 locus match with entry number", j))
 }
  } 

我的输出只是一个配置文件列表。我如何添加有多少?

列表在我的控制台中如下所示:

[1] "!!! 1 locus match with entry number 4"

[1] "!!! 1 locus match with entry number 7"

[1] "!!! 1 locus match with entry number 24"

[1] "!!! 1 locus match with entry number 44"

[1] "!!! 1 locus match with entry number 51"

[1] "!!! 1 locus match with entry number 53"

[1] "!!! 1 locus match with entry number 58"

[1] "!!! 1 locus match with entry number 63"

[1] "!!! 1 locus match with entry number 72"

等等……

【问题讨论】:

  • 除了将 i 的值设置为 1 之外,您对 i 的 for 循环不会做任何事情。要么您不需要该 for 循环,只需将 i 设置为 1,要么您顺序有误。此外,假设您的 for 循环 i 在 1:1035 中运行(比如说)i,您现在可能会多次找到匹配项,使 nMatchingLoci 大于 1,这将导致声明您的 if 语句失败来一场比赛。

标签: r for-loop if-statement rstudio


【解决方案1】:

在 for 循环之前创建一个值为 0 (x=0) 的变量。然后在第二个 if 语句中添加
x=x+1

然后在运行 for 循环后打印 x 的值。那是你的数。

【讨论】:

    【解决方案2】:

    我建议使用向量或列表来存储“位点匹配”的索引,然后在循环完成后您可以计算条目。

    我个人会使用列表,因为它更通用(但使用起来有点挑剔)

    ## Preallocate list
    matchList <- vector("list",1036)
    
    for(j in 2:1036) {
      for(i in 1:1) {
        if(sampGeno[1,i]==FGMMdata[1,i,j] && sampGeno[2,i]==FGMMdata[2,i,j]) {
          matchList[[j]] <- c(matchList[[j]],i)
        }
      }
    } 
    
    ## indexes i where match was found for j=73
    matchList[[73]]
    
    ## Number of matches for each j index
    lengths(matchList)
    
    ## Total number of matches
    sum(lengths(matchList))
    

    正如我在评论中所说,我正在假设 i 上的 for 循环超出 1:1 以外的序列。

    【讨论】:

    • “我们进入了第二个圈子,这里住着贪吃的人”。唉,唉,你们通过种植对象偶然发现了The R Inferno的第2章。
    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多