Try this. # the data y <- sample(0:1, 50, replace=T) # response x1 <- sample(0:1, 50, replace=T) # explanatory var x2 <- sample(0:1, 50, replace=T) # explanatory var
# the number of regressors nregressors <- 2 # all possible combinations comb <- as.matrix(expand.grid(rep(list(0:1), times=nregressors))) dimnames(comb)[[2]] <- paste0("x", 1:nregressors) # create empty list for nls fits allModelsList <- vector("list", dim(comb)[1]) # fit the nls models for(i in seq(allModelsList)) { # the selected regressors sel.regressors <- (1:nregressors)[comb[i, ]==1] if(length(sel.regressors) > 0) { # create the formula snippet <- paste0("(a", sel.regressors, " * x", sel.regressors, ")", collapse=" + ") my.formula <- paste0("y ~ exp(c + ", snippet, ")/ (1 + exp(c + ", snippet, "))") # create the list of starting values my.start <- as.list(c(0.2, rep(-0.2, length(sel.regressors)))) names(my.start) <- c("c", paste0("a", sel.regressors)) # fit the nls model allModelsList[[i]] <- nls(my.formula, start=my.start) } else { # if no regressors were selected allModelsList[[i]] <- nls(y ~ exp(c) / (1 + exp(c)), start=list(c=0.2)) } } # look at the results allModelsList Jean mael <henriksson.a...@live.se> wrote on 08/23/2012 10:19:38 AM: > > Hi all, > > I am trying to make a script that prints all possible models from a model > I've created using nls(). It is a logisitc model which in total includes 13 > variables. So its >8000 models I need to create, which I don't want to do > manually. I've tried modify scripts made for linear models with no results. > > I've tried these scripts on a two variable model (c,a1 and a2 is what I want > to estimate here. Where c is a constant and a1 and a2 is a weight for x1 and > x2): > > x1<-sample(0:1,50,replace=T)#explanatory var > x2<-sample(0:1,50,replace=T)#explanatory var > y<-sample(0:1,50,replace=T)#response > # first script I've tried > mod <- list() > for (i in 1:3) { > mod[[i]] <- nls(y~exp(c+(a1*x1)+(a2*x2) > )/ > (1+exp(c+(a1*x1)+(a2*x2))) > ,start=list(a1=-0.2,a2=-0.2,c=0.2)) > print(summary(mod[[i]])) > } > > #second script I've tried > regressors<-c("x1","x2") > regMat<-expand.grid(c(T,F),c(T,F)) > regMat > > allModelsList <- apply(regMat,1, > function(x)as.formula(nls(y~exp(c+(a1*x1)+(a2*x2) > )/ > (1+exp(c+(a1*x1)+(a2*x2))) > ,start=list(a1=-0.2,a2=-0.2,c=0.2)))) > > allModelsList > allModelsResults <- lapply(allModelsList, > function(x) nls(x, > start=list(a1=-0.2,a2=-0.2,c=0.2))) > allModelsResults > > They both give me the same models repeatedly, which is not what I wanted. > Any suggestions on how to do this? Please help. > Thanks! > Anna [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.