# [R] Combination of variables

Mon Jan 22 15:05:12 CET 2007

```You might find the following code useful.  It's part of a package I'm
developing for interactive model exploration.

# Generate all models
# Fit all combinations of x variables (\$2^p\$)
#
# This technique generalises \code{\link{fitbest}}.  While it is much
# slower it will work for any type of model.
#
# @arguments vector y values
# @arguments matrix of x values
# @arguments method used to fit the model, eg
# @keyword regression
fitall <- function(y, x, method=lm, ...) {
data <- cbind(y=y, x)

combs <- do.call(expand.grid, rep(list(c(FALSE, TRUE)), ncol(x)))[-1, ]

vars <- apply(combs, 1, function(i) names(x)[i])
form <- paste("y ~ ", lapply(vars, paste, collapse=" + "), sep = "")
form <- lapply(form, as.formula)

models <- lapply(form, function(f) eval(substitute(method(f,
data=data, ...), list(f=f, data=data, method=method))))
names(models) <- 1:length(models)
class(models) <- c("ensemble", class(models))
models
}

# Generate best linear models
# Use the leaps package to generate the best subsets.
#
# @arguments model formula
# @arguments data frame
# @arguments number of subsets of each size to record
# @arguments other arguments passed to \code{\link[leaps]{regsubsets}}
# @keyword regression
fitbest <- function(formula, data, nbest=10, ...) {
b <- regsubsets(formula, data=data, nbest=nbest, ...)
mat <- summary(b, matrix.logical = TRUE)\$which

intercept <- c("", "-1")[as.numeric(mat[,1])]
vars <- apply(mat[,-1], 1, function(x) colnames(mat[, -1])[x])
form <- paste(formula[], " ~ ", lapply(vars, paste, collapse=" +
"), sep = "")
form <- lapply(form, as.formula)

models <- lapply(form, function(f) eval(substitute(lm(f, data=data),
list(f=f, data=data))))
names(models) <- 1:length(models)
class(models) <- c("ensemble", class(models))
models
}

On 22 Jan 2007 08:51:22 -0000, anil kumar rohilla
<anil_rohilla at rediffmail.com> wrote:
>
> Hi,
>  List , i have 6 predictor variables and i want to make possible combinations of these 6 predictors ,all the data is in matrix form ,
> if i am having 6 predictors than possible combination of sets are 64 2 power 6, or 63 ,whatever it may be i want to store the result in another variable to each combination and that i want to put in some model ,
>
> i want to put every combination in some model ,please help me how to find suitable combinations of these variables ........
>
> i was not able to do this .
> Any package is there in R which can help me in this regards
> any help .
>
>
> ANIL KUMAR( METEOROLOGIST)
> LRF SECTION
> NATIONAL CLIMATE CENTER
> INDIA METEOROLOGICAL DEPARTMENT
> SHIVIJI NAGAR
> PUNE-411005 INDIA
> MOBILE +919422023277
> anilkumar at imdpune.gov.in
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help