Find the indices of the odd numbers in an integer vector
11,282
Solution 1
> which(someVector %% 2 == 1)
[1] 1 2 5 6 8
Solution 2
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 !
Author by
TovrikTheThird
Updated on June 09, 2022Comments
-
TovrikTheThird almost 2 years
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 elementsso in this case it would look like...
resultVector = c(1, 2, 5, 6, 8)
-
GSee over 11 yearsWow! There's a lot of code in that
is.odd
function. Why is that better thanis.odd <- function(x) x %% 2 == 1
? ... Also, looks like that will be slower since it's growing a vector in a while loop (even though the function already knows the length of the output) -
agstudy over 11 years@GSee you 're right , I saw this mee too I hope I will not dwonvoted for this stupid function :)
-
GSee over 11 yearsLook at how ugly this is:
suppressMessages(is.odd(c(0, 2, 0, 1, 0)))
. Wonder why the author doesn't accept that 0 is even. en.wikipedia.org/wiki/Parity_of_zero -
agstudy over 11 years@GSee really dirty and ugly:)tha's said , it the school package. The idea maybe to show the algorithm (implements the modulo division)
-
flodel over 11 years+1 for "don't use this function!". It is so ugly it is funny.
-
Marjolein Fokkema over 2 yearsExactly what an odd function should look like