[R] Automatic formula creation

Alex van der Spek doorz at xs4all.nl
Fri Aug 9 12:40:27 CEST 2013


Say I want to compare all 5 term models from a choice of 28 different 
predictors and one known. All possible combinations of 5 out of 28 is 
easy to form by combn(). With some string manipulation it is also easy 
to make a text representation of a formula which is easy to convert by 
as.formula() for use in lm().

The primitive part however is pasting together the terms which I do 
explicitly for 5 terms, like so:


     ftext <- paste(terms[1], terms[2], terms[3], terms[4], terms[5],  
sep = ' * ')


Works but is not great as I now need to edit this formula when the 
number of terms changes. There ought to be a better way but I can't find it.

Any help much appreciated! The full block of relevant code follows:
Alex van der Spek

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++


#Try all 3 band models
nbands <- 5
freqs <- c('4', '5', '6_3', '8', '10', '12_7', '16', '20', '25', '32', 
'40', '51', '64', '81', '102', '128',
            '161', '203', '256', '323', '406', '512', '645', '813', 
'1024', '1290', '1625', '2048')
bands <- paste(rep('kHz', 28), freqs, rep('_ave', 28), sep = '')
nc <- choose(28, nbands)
combs <- t(combn(bands, nbands))

models <- vector("list", nc)
for (ic in 1:nc) {
     terms <- c()
     for (jc in 1:nbands) {
         t <- paste('log10(', combs[ic, jc], ')', sep = '')
         terms <- append(terms, t)
     }

     ftext <- paste(terms[1], terms[2], terms[3], terms[4], terms[5],  
sep = ' * ')

     ftext <- paste('I(1 - Pass149) ~ ', ftext, ' - 1', sep = '')
     forml <- as.formula(ftext)

     plus100.lm <- lm(forml, data = sd, subset = Use == 'Cal')
     plus100.sm <- step(plus100.lm, trace = 0)
}



More information about the R-help mailing list