# Modeling heteregenous within group variance using nlme and lme4

Consider the following data set (given at the end of the question):

library(ggplot2)
ggplot(r,aes(x=f1,y=y,color=f2))+geom_boxplot()


I would like to model heterogeneity of variance for group G1 and G2 i.e. $$y_{i}= \alpha_{f_1(i)}+\beta_{f_2(i)}+\epsilon_{i,f_1(i)}$$

$$\epsilon_{i,f_1(i)} \sim N(0,\sigma^2_{f_1(i)})$$

I understand that I can deal with this situation using gls in the following way (is this right?):

library(nlme)
gls(y~f1+f2,data=r,weights=varIdent(form=~1|f1))


Can I model the same using lme4 ?

Dataset:

    r=structure(list(y = c(-1.1316848130928, -0.396385594646378, 0.589690880032218,
1.52321001912788, 0.390206765971789, -0.509282412635648, -0.725329736745712,
2.50210743407235, 0.677569006955778, 0.546293721541106, 0.928337039971113,
0.335722723953903, 1.09606155785715, 0.272679200873732, 1.04494107739702,
-0.233868295453055, -1.73712355434937, 0.66453596677335, 0.301670616352279,
1.98486059866201, 1.55151382625759, 1.32067952567205, 0.0530713533439635,
-5.68894059915804, -0.62963609076646, 4.60610931183804, -2.89621567919518,
-1.56512624418944, -1.10723477595581, 2.14274736934952, 0.146245941642455,
3.44615219319318, 5.58531974836602, 4.37660570630301, 2.49834207960278,
2.05485687567195, 4.49542423692705, 3.75639698016655, 3.26594495479936,
-0.153851788423289), f1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("G1", "G2"), class = "factor"), f2 = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("C1", "C2"), class = "factor")), .Names = c("y",
"f1", "f2"), row.names = c(NA, -40L), class = "data.frame")

• In general, no. But you can fit a mixed model including a variance structure with lme. – Roland Dec 8 '17 at 9:37
• @Roland. Does it mean that it is possible when the variance structure is know e.g. sigma_{G1} = 2 sigma_{G2} ? – peuhp Jan 18 '18 at 10:23
• where the 2 is a coefficient that is estimated by the model. But you can also model the variance in dependence of a continuous covariate. – Roland Jan 18 '18 at 13:09
• @Roland thanks for your reply. But if the coefficient "2" is estimated, I do not see why the model in my question cannot be written for lmer ? can you help me to understand ? can you provide an example ? thanks – peuhp Jan 19 '18 at 9:03
• lme4 doesn't offer facilities for fitting variance heterogeneity models. You are welcome to contribute code to lme4 that implements this. – Roland Jan 19 '18 at 10:23