[R] Fitting a line on trellis plot

S Ellison S.Ellison at LGCGroup.com
Wed Mar 25 14:48:20 CET 2015


 
> Call:
> lm(formula = curr_data[[tmin_col]] ~ curr_data[[year_col]] -
>     1 | curr_data[[month_col]])


First, this is not a sensible formula for lm; lm() does not use '|' to denote grouping. It would be a valid formula for xyplot, in which | specifies grouping variables. In lm(), '|' is simply being treated as 'or', which is why one of your coefficients is for ' curr_data[[year_col]]  | curr_data[[month_col]]TRUE'

Second, you should not normally need things like curr_data[[month_col]], either in lm or xyplot. If curr_data is a data frame, things like

lm(tmin ~ year, data=curr_data)
 
should work.

Third, 'nested' models in lm use the nesting operator '/', not '|'. So if you want 12 lines with separate intercept and gradient from an lm, you need (with month as a factor and the default intercept suppressed)
lm(tmin~month+year/month -1, data=curr_data) #-1 suppresses the intercept and provides a zero-based intercept for each month

This gives you 12 'month' intercepts and one gradient per month. If you wanted a common intercept you'd do 
lm(tmin~ year/month, data=curr_data)
But beware; the coefficients in both cases cannot be interpreted as a simple gradient and intercept for each month: if I recall correctly, the gradients for month2 and on are modelled as an additive increment on the first month gradient. Use predict() if you want an easy way to predict a value for a given (possibly fractional) time of year and 'month'.
[Incidentally I don’t immediately see why that is a sensible thing to do - this fits a monthly summary against a numeric year. But I'm going to assume you know what you want there.]

Finally, though, this model will not help you much with lattice as there's no _simple_ way of putting those lines on different panels in a lattice plot. If you just want a line on each of 12 panels, that's much easier. You can  use the panel() function with panel.lmline to put it there. For example, if you want to plot a line over the data, use 

xyplot(tmin~year|month, curr_data,
	panel=function(x, y, ...) {
		panel.xyplot(x, y, ...)
		panel.lmline(x, y, ...)
	}
)


S Ellison




*******************************************************************
This email and any attachments are confidential. Any use, copying or
disclosure other than by the intended recipient is unauthorised. If 
you have received this message in error, please notify the sender 
immediately via +44(0)20 8943 7000 or notify postmaster at lgcgroup.com 
and delete this message and any copies from your computer and network. 
LGC Limited. Registered in England 2991879. 
Registered office: Queens Road, Teddington, Middlesex, TW11 0LY, UK


More information about the R-help mailing list