Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Function for returning ALL factors

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.

like image 401
JD Long Avatar asked Jun 21 '11 11:06

JD Long


People also ask

What is the as factor function in R?

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.

What R function is used to encode a vector as a category?

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.


1 Answers

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  
like image 189
Chase Avatar answered Sep 24 '22 01:09

Chase