我在 R 中有这个函数:
is.evenplus3 <- function(x) {
y <- x[which(x %% 2 == 0)]
a <- y + 3
return(a)
}
它基本上采用类似于简单序列的数字向量,例如 2:20,并返回所有偶数加 3。
> x <- 2:20
> is.evenplus3(x)
[1] 5 7 9 11 13 15 17 19 21 23
我使用 for
循环实现了基本相同的功能:
is.even.plus3.for <- function(x) {
for (i in x) {
if (i %% 2) {
next
}
print(i + 3)
}
}
返回相同的结果,但像这样:
> is.even.plus3.for(x)
[1] 5
[1] 7
[1] 9
[1] 11
[1] 13
[1] 15
[1] 17
[1] 19
[1] 21
[1] 23
两个问题:
- 我想让第二个函数返回相同的结果,但在单个向量中,就像第一个函数一样。想不通...
- 我想创建与第一个函数相同的函数,结果与第一个函数相同,但使用的是
while
循环,而不是for
循环。我试过了,但结果是一个无限循环...
最佳答案
这应该可行
x <- 2:20
# return even values from x. just to be sure everything is working as expected
x[which(x %% 2 == 0 )]
[1] 2 4 6 8 10 12 14 16 18 20
# add 3
x[which(x %% 2 == 0 )] + 3
[1] 5 7 9 11 13 15 17 19 21 23
注意这适用于任意向量
# arbitrary vector
y <- c(1,8,4,2,100,7,9)
y[which(y %% 2 == 0 )]
[1] 8 4 2 100
y[which(y %% 2 == 0 )] + 3
[1] 11 7 5 103
识别偶数的来源:http://r.789695.n4.nabble.com/identifying-odd-or-even-number-td2275447.html
关于r - 使用 while 循环从向量中取出所有偶数并将每个偶数加 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41226455/