-2

How do I specify random factors in R ?

If I have a factor x1 which is supposed to be random , can I try something like this ?

lm(y ~ x1, data = p)
jogo
  • 12,469
  • 11
  • 37
  • 42
TKBell
  • 33
  • 1
  • 4
  • Sorry, what are you trying to achieve ? Do you want to create some random factors, or do you want to do a linear regression against two factors of a data frame ?, some example data + code would really help... – PaulHurleyuk Mar 14 '10 at 20:31
  • So if I try lme4(y ~ x1, data = p), will x1 be treated as a random factor ? –  Mar 15 '10 at 18:35
  • 1
    I suspect x1 will be treated as "Error: could not find function "lme4"" since there is no function named lme4. – JD Long Mar 15 '10 at 19:56

3 Answers3

5

Most simply (using the older nlme rather than the new lme4),

library(nlme)
lme(fixed = y ~ 1, random = ~1|x1, data = p)

The equivalent in lme4 is:

library(lme4)
lmer(y~1+(1|x1), data = p)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
4

Are you by chance looking for the lme4 package which is focussed on linear mixed-effects (ie. fixed versus random) modelling?

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • if I write lm(y ~ x1, data = p), x1 will be treated as a fixed factor in R , Im wondering if there is way in R to specify that x1 is a random factor – TKBell Mar 14 '10 at 21:28
  • 3
    Yes, in the **lme4** package. Follow the link in my answer and read up on the documentation of the lme4 package. The `lm()` function is for basic linear modelling and does **not** support random effects. – Dirk Eddelbuettel Mar 14 '10 at 22:33
2

Zuur et al 2011, Mixed Effects Models and Extensions in Ecology with R, has an excellent walk through of random effects using the nlme package. They explain the differences between fixed, random, and mixed models and how to specify random intercepts and random slopes.

N Brouwer
  • 4,778
  • 7
  • 30
  • 35