Why is Filter failing to take factors of a number?

Viewed 47

I'm getting some strange behavior from some R code that I wrote to factor non-zero integers.

factors<-function(num) c(Filter(function(x) num%%x==0,(-num%/%2):num%/%2),num,-num)

I expected factors(-15) to give the sequence -15, -5, -3, -1, 1, 3, 5, 15. Instead, I get:

> factors(-15)
 [1]   3   3   1   1  -1  -1  -3  -3  -5  -5 -15  15

On top of being ordered very strangely (shouldn't it have checked from -7 to 7?) this misses out 5. What have I overlooked?

1 Answers

You missed a couple of brackets

factors <- function(num) c(-num, Filter(function(x) num%%x==0, (-num%/%2):(num%/%2)), num)
factors(-15)
# [1]  15   5   3   1  -1  -3  -5 -15

By the way, it checks from -8 to 7 in this case

(-15%/%2):(15%/%2)
# [1] -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7
Related