Structure of data
Your data are nested, and here is how I would code it, given your research question:
Level 2: You have 12 different tanks, each of which should have a unique ID number coded as factor
(I will code this as tankID
). At the tank level, you have two independent variables: genetic family (I will code it as genfam
, which is a dichotomous factor
) and treatment (I will code it as treat
, which is a dichotomous factor
).
Level 1: You have $n$ fish, each of which should have a unique ID number coded as factor
(I will code this as fishID
). You have one independent variable at this level: sex (which I will code as sex
, a dichotomous factor
). Your dependent variable is at this level (as is the case with multilevel models generally): survival (which I will code as survival
, which I assume is either int
, num
, or dbl
).
Your data should look something like:
fishID tankID genfam treat sex survival
1 1 A A M 12
2 2 A B F 8
... ... ... ... ... ...
...and so on.
Model code
I will skip the mathematical/Greek notation, unless you are into that. Since you said you are coding in R, I'll go right to how to code it. I would use the lme4
and lmerTest
packages to run your model. I will code your data as data
. The saturated model would be:
lmer(survival ~ sex * treat * genfam + (1 + sex | tankID), data=data)
What this is saying is that survival
is predicted by a three-way interaction between your independent variables of interest (R will automatically fill in all main effects and two-way interactions for you). The stuff in parentheses are the random parts of the model. 1
specifies that there is a different intercept for each tank—called a "random intercept." The sex
here means that the effect of sex is allowed to differ across different tanks as well—called a "random slope." The pipe |
means that these effects are nested within tank, called tankID
. I should also note that genfam
and treat
are not included here, because they are at Level 2, so the effects of genfam
and treat
cannot vary by Level 2 clusters.
lme4
does not like testing hypotheses with p-values and t-tests, especially since the degrees of freedom for multilevel models aren't straightforward, so the package lmerTest
will automatically add degrees of freedom approximations and p-values. Another option is running likelihood ratio tests with the anova
function and using nested models, but with so many predictors in your model, this would likely be too much of a hassle (and I find that the likelihood ratio and lmerTest
rarely disagree).