在一个整数向量中找到奇数的索引

7

假设我们有一个向量:

someVector = c(1, 3, 4, 6, 3, 9, 2, -5, -2)

我希望获得一个向量,其中包含所有奇数元素在 someVector 中的位置。

因此,在这种情况下,它看起来像...

resultVector = c(1, 2, 5, 6, 8)
2个回答

11
> which(someVector %% 2 == 1)
[1] 1 2 5 6 8

7
library(schoolmath)
which(is.odd(someVector))
[1] 1 2 5 6 8

仅供娱乐,以下是is.odd函数的代码:

function (x) 
{
  start <- 1
  end <- length(x) + 1
  while (start < end) {
    y <- x[start]
    if (y == 0) {
      cat("Please enter a number > 0")
      end
    }
    test1 <- y/2
    test2 <- floor(test1)
    if (test1 != test2) {
      if (start == 1) {
        result = TRUE
      }
      else {
        result <- c(result, TRUE)
      }
    }
    else {
      if (start == 1) {
        result = FALSE
      }
      else {
        result <- c(result, FALSE)
      }
    }
    start <- start + 1
  }
  return(result)
}

绝对不要使用这个函数!

2
哇!那个 is.odd 函数里有很多代码。为什么它比 is.odd <- function(x) x %% 2 == 1 更好呢?此外,看起来它会更慢,因为它在 while 循环中增加了一个向量(即使函数已经知道输出的长度)。 - GSee
@GSee,你说得对,我也看到了。希望我不会因为这个愚蠢的函数而被投票否决 :) - agstudy
1
看看这个多么丑陋:suppressMessages(is.odd(c(0, 2, 0, 1, 0)))。不知道为什么作者不接受0是偶数。http://en.wikipedia.org/wiki/Parity_of_zero - GSee
@GSee 真的很丑陋:) 但这是学校的套餐。也许想要展示算法(实现模除)。 - agstudy
3
+1表示“不要使用这个函数!”。这个函数很丑,但也很有趣。 - flodel
一个奇函数应该长什么样子,就是这个意思。 - Marjolein Fokkema

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接