假设我们有一个向量:
someVector = c(1, 3, 4, 6, 3, 9, 2, -5, -2)
我希望获得一个向量,其中包含所有奇数元素在 someVector
中的位置。
因此,在这种情况下,它看起来像...
resultVector = c(1, 2, 5, 6, 8)
> which(someVector %% 2 == 1)
[1] 1 2 5 6 8
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)
}
is.odd
函数里有很多代码。为什么它比is.odd <- function(x) x %% 2 == 1
更好呢?此外,看起来它会更慢,因为它在 while 循环中增加了一个向量(即使函数已经知道输出的长度)。 - GSeesuppressMessages(is.odd(c(0, 2, 0, 1, 0)))
。不知道为什么作者不接受0是偶数。http://en.wikipedia.org/wiki/Parity_of_zero - GSee