user3542110 user3542110 - 1 year ago 65
R Question

Writing a loop in R that updates a model

I am looking for a way of adding terms to a model. Here's what I currently have:

model = lm(min.temp ~ latitude + longitude)
for (i in 1:10) {

model = update(model, .~.+I(latitude^i))

//do calculations on the current model here..


The problem is, when I run this function and then summarize the final model, it only includes latitude, longitude and latitude^i. What I'd like to obtain is a final model that shows latitude, longitude, latitude^1, latitude^2, latitude^3,...latitude^10.

This is a simplified version of the loop I need. Basically I want to add a term that depends on the particular loop it is added. I have no idea how to get the value in stead of the "i".


Answer Source

Try this:


Your code doesn't work, because it is formula and R takes it 'as is'. It does not resolve variable i to value 1,2,...10. So you need to paste i first with rest of the formula and then tell R it is formula.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download