2013-01-11 12 views

Odpowiedz

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

tylko dla zabawy tutaj Kodeksu funkcji 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) 
} 

Zdecydowanie, nie należy używać tej funkcji!

+2

Wow! W funkcji 'is.odd' jest dużo kodu. Dlaczego jest to lepsze niż 'is.odd <- function (x) x %% 2 == 1'? ... Wygląda na to, że będzie wolniej, ponieważ rośnie wektor w pętli while (nawet jeśli funkcja zna już długość wyjścia) – GSee

+0

@GSee, masz rację, widziałem też to mee nie dwuznaczne za tę głupią funkcję :) – agstudy

+1

Zobacz, jak brzydko to jest: 'suppressMessages (is.odd (c (0, 2, 0, 1, 0)))'. Zastanawiam się, dlaczego autor nie akceptuje tego, że zero jest równe. http://en.wikipedia.org/wiki/Parity_of_zero – GSee

Powiązane problemy