首页 > 解决方案 > 当 for 循环中的 if 语句为 false 并且我不想对 false 进行任何操作然后直接测试下一个值时,我该怎么办?

问题描述

我想在 0 到 100 之间找到 2 的倍数,并将这些倍数保存在向量中。这是我的代码:

i <- c(0:100)
a <- c()
for (value in i) {
  if (i %% 2 == 0) {
    a[i+1] <- i
  }
}
#> Warning in if (i%%2 == 0) {: the condition has length > 1 and only the first
#> element will be used

#> Warning in if (i%%2 == 0) {: the condition has length > 1 and only the first
#> element will be used

#> Warning in if (i%%2 == 0) {: the condition has length > 1 and only the first
#> element will be used
...
print(a)
#>   [1]   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
#>  [19]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
#>  [37]  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
#>  [55]  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
#>  [73]  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
#>  [91]  90  91  92  93  94  95  96  97  98  99 100
Created on 2020-06-12 by the reprex package (v0.3.0)

我期望的结果应该是“0,2,4,6,8,10,12...”。

我哪里错了?

标签: rfor-loopif-statement

解决方案


基于“a”的初始化方式(即作为NULL向量),我们可以连接满足if条件的“值”

a <- c()
for(value in i) if(value %%2 == 0) a <- c(a, value)

a
#[1]   0   2   4   6   8  10  12  14  16  18  20  22  24  26  28  30  32  34  36  38  40  42  44  46  48  50  52  54  56  58  60  62  64  66
#[35]  68  70  72  74  76  78  80  82  84  86  88  90  92  94  96  98 100

在 OP 的代码中,内部条件if是使用整个向量i而不是“值”完成的,从而导致警告消息,因为if/else需要 TRUE/FALSE 的单个元素


这可以在没有循环的情况下完成,R因为这些是矢量化操作

i[!i %% 2] 

推荐阅读