lev2bool: Conversion of factor to 0/1 variable

View source: R/extractors.R

lev2boolR Documentation

Conversion of factor to 0/1 variable

Description

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.

Usage

lev2bool(fac, lev)

Arguments

fac

An object coercible to factor.

lev

The level of fac to be converted to 1.

Value

A one-column matrix.

See Also

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.

Examples

## 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))

spaMM documentation built on June 22, 2024, 9:48 a.m.

Related to lev2bool in spaMM...