user3542110 - 8 months ago 40

R Question

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".

Thanks!

Answer

Try this:

```
update(lm1,as.formula(paste0(".~.+I(latitude^",i,")")))
```

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.

Source (Stackoverflow)