In reading R for programmers I saw this function
oddcount <- function(x) {
k <- 0
for (n in x) {
if (n %% 2 == 1) k <- k+1
}
return(k)
}
I would prefer to write it in a simpler style (i.e in lisp)
(defn odd-count [xs]
(count (filter odd? xs)))
I see the function length is equivalent to count and I can write odd? so are there built-in map/filter/remove type functions?
A more R way to doing this would be to avoid the
forloop, and use vectorization:The comparison between
xand 2 outputs a vector asxitself is a vector. Sum than calculates the sum of the vector, whereTRUEequals 1 andFALSEequals zero. In this way the function calculates the number of odd numbers in the vector.This already leads to more simple syntax, although for non-vectorization-oriented people the
forloop tends to be easier to read. I greatly prefer the vectorized syntax as it is much shorter. I would prefer to use a more descriptive name forxthough, e.g.number_vector.