predict values from GAM for grouped dataframe in R
Another option is to fit a model that allows the lat/temp relationship to vary by year. There are several options for this. The following fits a model where each year has an independent relationship:
gam(lat ~ year + s(temp, by = year), data = dat)
Note that for this formulation year
should be encoded as a factor.
An alternative would be to allow the lat/temp relationship to vary smoothly by year, a reasonable model if this relationship gradually changes over time. In this case you will want to use a tensor product smooth (te()
) to indicate a two-way interaction between variables that are on different scales (degrees, years):
gam(lat ~ te(temp, year), data = dat)
In both cases you can then make a prediction with predict.gam(model, newdata = new_dat)
, where new_dat
has both year
and temp
columns.