[R] using lme and 'by' function to extract the co-efficients by individuals

Ben Bolker bbolker at gmail.com
Mon Oct 24 18:30:46 CEST 2011


tom_pienkowski <tom.pienkowski <at> blueyonder.co.uk> writes:

> I'm trying to use the 'by' function to extract the co-efficients from a
> mixed model which is performed on multiple individuals. I basically have a
> group of individuals and for each individual I want the co-efficient for
> there change in 'pots_hauled' in response to a change in 'vpue' with my
> random variable being 'ns_a_vpue'. 
> 
> The problem I am having is that the co-efficients for all my individuals are
> returning as the same! So I'm not getting the individuals co-efficients, I'm
> not even sure what it is returning. Here is a sample of my code:
> 
> mod_1 <- lme(pots_hauled ~ rc_a_vpue ,(random = ~1 | a_vpue), data = data1)
> 
> by(data1, id, summary)
> 
> by(data1, list(pots_hauled=pots_hauled,id=id ), summary)
> 
> by(data1, id, function(x) lme(pots_hauled ~ a_vpue ,(random = ~1 |
> ns_a_vpue), data = data1)))
> 
> lmid <- by(data1, id, function(x) lme(pots_hauled ~ a_vpue ,(random = ~1 |
> ns_a_vpue), data = data1))
> 
> sapply(lmid, coef)
> 

  I think your problem is that you're specifying "data=data1" in your
function call, which means that by() doesn't get a chance to substitute
the correct individual-specific data.  I would suggest

lmid <- by(data1, id, lme,
   fixed= pots_hauled ~ a_vpue ,
   random = ~1 | ns_a_vpue)

which should automatically insert the appropriate chunk of
'data1' as the data= argument in lme.

  I would further suggest that you probably want sapply(lmid,fixef)
rather than sapply(lmid,coef) (which will return the coefficients
for each random-effects level within individuals)

  I would furthermore suggest that you might want to (a)
consider using a multilevel random-effects model where
individuals were also a random effect (rather than testing
each individual separately and (b) send followups to
r-sig-mixed-models at r-project.org (the special interest
group on mixed models)

  Ben Bolker



More information about the R-help mailing list