Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lapply function to pass single and + arguments to LM

Tags:

r

I am stuck trying to pass "+" arguments to lm.

My 2 lines of code below work fine for single arguments like:

model_combinations=c('.', 'Long', 'Lat', 'Elev')


lm_models = lapply(model_combinations, function(x) {
                               lm(substitute(Y ~ i, list(i=as.name(x))), data=climatol_ann)})

But same code fails if I add 'Lat+Elev' at end of list of model_combinations as in:

model_combinations=c('.', 'Long', 'Lat', 'Elev', 'Lat+Elev') 

Error in eval(expr, envir, enclos) : object 'Lat+Elev' not found

I've scanned posts but am unable to find solution.

like image 915
Robert Cruickshank Avatar asked Dec 21 '25 15:12

Robert Cruickshank


1 Answers

I've generally found it more robust/easier to understand to use reformulate to construct formulas via string manipulations rather than trying to use substitute() to modify an expression, e.g.

model_combinations <- c('.', 'Long', 'Lat', 'Elev', 'Lat+Elev')
model_formulas <- lapply(model_combinations,reformulate,
                         response="Y")
lm_models <- lapply(model_formulas,lm,data=climatol_ann)

Because reformulate works at a string level, it doesn't have a problem if the elements are themselves non-atomic (e.g. Lat+Elev). The only tricky situation here is if your data argument or variables are constructed in some environment that can't easily be found, but passing an explicit data argument usually avoids problems.

(You can also use as.formula(paste(...)) or as.formula(sprintf(...)); reformulate() is just a convenient wrapper.)

like image 152
Ben Bolker Avatar answered Dec 23 '25 05:12

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!