My normal search foo is failing me. I'm trying to find an R function that returns ALL of the factors of an integer. There are at least 2 packages with factorize()
functions: gmp and conf.design, however these functions return only prime factors. I'd like a function that returns all factors.
Obviously searching for this is made difficult since R has a construct called factors which puts a lot of noise in the search.
The as. factor() is a built-in R function that converts a column from numeric to factor. The as. factor() method takes column or data frame x as an argument and returns the requested column specified as a factor rather than numeric.
The function factor is used to encode a vector as a factor (the terms 'category' and 'enumerated type' are also used for factors). If argument ordered is TRUE , the factor levels are assumed to be ordered.
To follow up on my comment (thanks to @Ramnath for my typo), the brute force method seems to work reasonably well here on my 64 bit 8 gig machine:
FUN <- function(x) { x <- as.integer(x) div <- seq_len(abs(x)) factors <- div[x %% div == 0L] factors <- list(neg = -factors, pos = factors) return(factors) }
A few examples:
> FUN(100) $neg [1] -1 -2 -4 -5 -10 -20 -25 -50 -100 $pos [1] 1 2 4 5 10 20 25 50 100 > FUN(-42) $neg [1] -1 -2 -3 -6 -7 -14 -21 -42 $pos [1] 1 2 3 6 7 14 21 42 #and big number > system.time(FUN(1e8)) user system elapsed 1.95 0.18 2.14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With