rmodellmeffects

Problem with effects function : how to get adjusted value from a model?


I encounter using "effect" from effects package. My goal is to extract the values of the fitted model for some values of my predictor. The problem is for a mixed model with quadratic predictors but it can be reproduced with a simple linear model.

Let's consider the following generated data :

y=rnorm(n = 12,mean = 10,sd = 3)
time=rep(c(0,1,6,10),3)
df=data.frame(time,y)

Now I fit a linear model and get the effect of "time" with the effect function :

model=lm(y~time, data=df)
fx=effect("time", model) 

I was assuming I could get the values of the model for my 4 time values with :

time=fx$x
values=fx$fit

But instead of my 4 time points fx$x returns a time vector with : 0 2 5 8 10

I don't understand why (but my guess is that I'm doing it wrong). I just wand to get the values of the model for my time points (0,1,6,10). How can I do (that will work too with a lme4::lmer model)?

Thanks in advance


Solution

  • By default, the effects package spaces values evenly over the range of the focal predictor. You can specify the values you want explicitly in the xlevels argument:

    library(effects)
    #> Loading required package: carData
    #> lattice theme set by effectsTheme()
    #> See ?effectsTheme for details.
    y=rnorm(n = 12,mean = 10,sd = 3)
    time=rep(c(0,1,6,10),3)
    df=data.frame(time,y)
    
    
    model=lm(y~time, data=df)
    fx=effect("time", model, 
              xlevels = list(time = unique(df$time)) )
    time=fx$x
    time
    #>   time
    #> 1    0
    #> 2    1
    #> 3    6
    #> 4   10
    values=fx$fit
    values
    #>       [,1]
    #> 1 9.629158
    #> 2 9.439073
    #> 3 8.488650
    #> 4 7.728311
    

    Created on 2024-01-26 with reprex v2.0.2