Please always send coding questions to the list directly. You will get better and faster
help there because there are many students that know the right answer (like John, Jon,
Albert, and Jeremy that just provided excellent answers to Keith's question).
To answer your question, there are many ways in R to check if a number is even or odd. For
example, if x is your scalar (such as the length of a vector) you could use:
ifelse(x %% 2, "action if x is odd", "action if x is even")
Notice that x %% y asks for x mod y, so x %% 2 will return 1 (TRUE) if x is odd and 0
(FALSE) if x is even, and ifelse() then implements one of two possible actions.
Check:
??%%?
?ifelse
For details. Hope this helps.
Jens
---------------------------------------------------------------
I have a question on 0.1b. This is what I have so far but I am stuck as to how to
determine if the length of the vector is even or odd:
newmed <- function(a) {
mediodd <- a[trunc(length(a)/2)+1]
mediev <- (a[length(a)/2]+a[length(a)/2+1])/2
if (length(a) is odd) return(mediodd)
if (length(a) is even) return(mediev)
}
Am I doing this in the right way?
Show replies by date