R 使用while循环从向量中获取所有偶数,并向每个偶数加3

R 使用while循环从向量中获取所有偶数,并向每个偶数加3,r,R,我在R中有这个函数: is.evenplus3 <- function(x) { y <- x[which(x %% 2 == 0)] a <- y + 3 return(a) } 返回相同的结果,但如下所示: > 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 两个问题: 我想让第二个函数返回相同的结果,但是在一个向量

我在R中有这个函数:

is.evenplus3 <- function(x) {
   y <- x[which(x %% 2 == 0)] 
   a <- y + 3
   return(a)
}
返回相同的结果,但如下所示:

> 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
    循环。我试过了,但结果是一个无限循环

    • 答案就在这里,希望你能从中学到一些东西

      a

      is.even.plus3.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
      

      x@Psidom:这是一个相当基本的问题,但似乎是一个合理的自学问题,OP已经做出了努力。对于OP:尝试(1)设置一个计数器
      j
      ,该计数器从1开始,仅在到达奇数
      i
      时递增;(2) 分配适当长度的向量
      结果
      (例如,使用
      数值()
      );(3) 将
      result[j]
      设置为所需的值,而不是打印是的,练习循环是一种练习,但遇到了困难(1)如果你尝试向OP解释事情,而不是仅仅给出答案,那会更有帮助。(2) 通过追加(
      res(1)您可能是对的。(2)在循环结束之前,所需向量的长度未知…(2)为真。对于本例来说,这有点先进,但可以留出比预期需要更长的向量,然后将其截断…@BenBolker同意:)
      
      > 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
      
      is.even.plus3.for <- function(x) {
      res <- numeric()
      for (i in x) {
       if (i %% 2) {
         next
       }
       res <- c(res,(i + 3))
      }
       return(res)
      }
      
      is.even.plus3.while <- function(x) {
          i <- 1
          res <- numeric()
          while(i <= length(x) + 1) {
              if (i %% 2) {
                  i <- i+1
                  next
              }
              res <- c(res,(i + 3))
              i <- i+1
          }
          return(res)
      }
      
      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