r - 当 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...”。
我哪里错了?
解决方案
基于“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]
推荐阅读
- android - 如何使本机库可选
- spring - 如何在 Spring Security 中使用 cookie 进行基本身份验证?
- javascript - 如何逐字打印数组Javascript
- reactjs - 我需要在客户端检查 JWT 过期吗?
- php - 单击Php中的按钮时,我想运行python文件(生成10个空白文本文件的程序)
- php - php printf 未按正确顺序打印
- maven - 当添加为依赖项目中的依赖项时,有没有办法引用 pom?
- java - 如果有人在java中失败,如何停止所有线程?
- swift - 为什么每次我尝试让用户在 Swift 中输入整数时,Xcode 都会让我输入“!” 在变量之后
- mysql - 删除 JSON 键中的前导和尾随空格