lev2bool | R Documentation |
It may be straightforward to add columns of indicator variables for each level of a factor to the data, by
<data> <- cbind(
<data>, model.matrix( ~
<factor> - 1, data =
<data>))
.
Alternatively, indicator variables can be created on the fly for given levels, using the lev2bool
function.
lev2bool(fac, lev)
fac |
An object coercible to |
lev |
The level of |
A one-column matrix.
Example in GxE
for alternative to using lev2bool
in specification of
random effects with heteroscedasticity, useful when the latter is controlled
by a factor with many levels.
## Elementary bivariate-response model
# Data preparation
#
fam <- rep(c(1,2),rep(6,2)) # define two biological 'families'
ID <- gl(6,2) # define 6 'individuals'
resp <- as.factor(rep(c("x","y"),6)) # distinguishes two responses per individual
set.seed(123)
toymv <- data.frame(
fam = factor(fam), ID = ID, resp = resp,
y = 1 + (resp=="x") + rnorm(4)[2*(resp=="x")+fam] + rnorm(12)[6*(resp=="x")+as.integer(ID)]
)
toymv <- cbind(toymv, model.matrix( ~ resp - 1, data = toymv))
# fit response-specific variances of random effect and residuals:
#
(fitme(y ~ resp+ (0+respx|fam)+ (0+respy|fam),
resid.model = ~ 0+resp ,data=toymv))
# Same result by different syntaxes:
# * by the lev2bool() specifier:
(fitme(y ~ resp+ (0+lev2bool(resp,"x")|fam)+ (0+lev2bool(resp,"y")|fam),
resid.model = ~ 0+resp ,data=toymv))
# * or by random-coefficient model using 'resp' factor:
(fitme(y ~ resp+ (0+resp|fam), resid.model = ~ 0+resp ,data=toymv,
fixed=list(ranCoefs=list("1"=c(NA,0,NA)))))
#
# For factors with more levels, the following function may be useful to specify
# through partially fixed ranCoefs that covariances are fixed to zero:
ranCoefs_for_diag <- function(nlevels) {
vec <- rep(0,nlevels*(nlevels+1L)/2L)
vec[cumsum(c(1L,rev(seq(nlevels-1L)+1L)))] <- NA
vec
}
# see application in help("GxE").
# * or by the dummy() specifier from lme4:
# (fitme(y ~ resp+ (0+dummy(resp,"x")|fam)+ (0+dummy(resp,"y")|fam),
# resid.model = ~ 0+resp ,data=toymv))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.