7

いくつかのベクトルがあるとしましょう:

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

someVectorすべての奇数要素の位置を含むベクトルを取得したい

したがって、この場合は次のようになります...

resultVector = c(1, 2, 5, 6, 8)
4

2 に答える 2

11
> which(someVector %% 2 == 1)
[1] 1 2 5 6 8
于 2013-01-11T19:09:39.767 に答える
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)
}

絶対に、この機能を使用しないでください。

于 2013-01-11T19:19:11.903 に答える