Search code examples
rloopsfor-looppolynomials

How to change the polynomial order in a for-loop using the poly R function?


I would like to fit a regression by trying different polynomials, and I tried running this loop:

for (p_order  in 1:9) {
  assign(paste("RD0", p_order, sep = ""),  electricity_price ~ d1 + gas_price + coal_price +
  oil_price + EUA +  weekday + month + median_windspeed1 + 
  median_windspeed2 +   median_windspeed3 +   median_windspeed4 + 
  sun1 + sun2 + sun3 + sun4 + median_temp1 +   median_temp2 + 
  median_temp3 + median_temp4 + poly(as.numeric(date), p_order, raw=TRUE) + time) 
}

Although it creates correctly the names of the variables (RD01, RD02, etc), instead of saving the correct order of the polynomial (1,2, etc) it stores "p_order". For example,

> RD04
electricity_price ~ d1 + gas_price + coal_price + oil_price + 
    EUA + weekday + month + median_windspeed1 + median_windspeed2 + 
    median_windspeed3 + median_windspeed4 + sun1 + sun2 + sun3 + 
    sun4 + median_temp1 + median_temp2 + median_temp3 + median_temp4 + 
    poly(as.numeric(date), p_order, raw = TRUE) + time
> RD07
electricity_price ~ d1 + gas_price + coal_price + oil_price + 
    EUA + weekday + month + median_windspeed1 + median_windspeed2 + 
    median_windspeed3 + median_windspeed4 + sun1 + sun2 + sun3 + 
    sun4 + median_temp1 + median_temp2 + median_temp3 + median_temp4 + 
    poly(as.numeric(date), p_order, raw = TRUE) + time

Could someone explain me why and how to sort this out?

Thank you!


Solution

  • Create the formula first, then assign it. I will post a simplified example.

    for (p_order  in 1:2) {
      fmla <- paste("electricity_price ~ d1 + poly(as.numeric(date),", p_order, ", raw = TRUE)")
      assign(paste("RD0", p_order, sep = ""),  as.formula(fmla)) 
    }
    
    RD01
    #electricity_price ~ d1 + poly(as.numeric(date), 1, raw = TRUE)
    RD02
    #electricity_price ~ d1 + poly(as.numeric(date), 2, raw = TRUE)