[R] Variable Combinations in Regression

Jim Lemon jim at bitwrit.com.au
Sat Jan 9 02:28:35 CET 2010


On 01/09/2010 07:49 AM, Richardson, Patrick wrote:

>  Let's say I have 8 variables and I want to generate all combinations
>  of those variables (In pairs, threes fours, etc) to run in multiple linear
>  regression. Is there a built-in function to do that in R?
>
>  Or at a minimum, how could I take those variables and generate all possible
>  combinations.
>

Hi Patrick,
Maybe what you want is this:

allComb<-function(x) {
  nx<-length(x)
  combs<-as.list(x)
  for(i in 2:length(x)) {
   indices<-combn(1:nx,i)
   for(j in 1:dim(indices)[2]) {
    xlist<-list(x[indices[,j]])
    combs<-c(combs,xlist)
   }
  }
  return(combs)
}

that returns a list of all combinations of all sizes. As David pointed 
out, there are going to be a lot of combinations with eight elements.

Jim



More information about the R-help mailing list