Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the indices of the odd numbers in an integer vector

Tags:

integer

r

Say we have some vector:

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

I want to get a vector that has the locations in someVector of all the odd elements

so in this case it would look like...

resultVector = c(1, 2, 5, 6, 8)
like image 812
TovrikTheThird Avatar asked Jan 11 '13 19:01

TovrikTheThird


2 Answers

> which(someVector %% 2 == 1)
[1] 1 2 5 6 8
like image 84
GSee Avatar answered Oct 19 '22 23:10

GSee


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

just for fun here the code of the is.odd function :

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)
}

Definitely , Don't use this function !

like image 24
agstudy Avatar answered Oct 19 '22 22:10

agstudy