nested_treatment_contrasts: Treatment contrasts for a nested factor

Description Usage Arguments Details Value Note Author(s) See Also Examples

Description

The function creates treatment contrasts for a factor whose levels are nested within the levels of another factor.

Usage

1
nested_treatment_contrasts(outer.factor, inner.factor)

Arguments

outer.factor

A factor.

inner.factor

A factor whose levels are nested in the levels of the outer.factor.

Details

The outer and inner factors need to have the same length. It can be the data that is used in a regression model, so it is allowed to have multiple instances of the inner factor in the inner.factor, but it can also be shorter factors that just describe the nesting.

The contrast matrix can be used directly on the inner factor using the funtion contrasts, but it is usually necessary to specify the argument how.many=nlevels(inner.factor) - nlevels(outer.factor).

The function superMatrix is used to make a block diagonal matrix.

Value

An object of class matrix with nlevels(inner.factor) rows and nlevels(inner.factor) - nlevels(outer.factor) columns.

Note

The nesting of the input vectors is not checked.

Author(s)

Johanna Bertl

See Also

contr.treatment, contrasts, nested_sum_contrasts

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Treatment contrasts for the cancer type and the sample ID, which is nested in the cancer type.

data("cancermutations")
small = droplevels(cancermutations[cancermutations$cancer_type %in% c("KICH", "LGG"),])

nesting = nested_treatment_contrasts(outer.factor=small$cancer_type, inner.factor=small$sample_id)
how.many = nlevels(small$sample_id) - nlevels(small$cancer_type)
contrasts(small$sample_id, how.many=how.many) = nesting

# Visualize contrast matrix: 
 
image(t(nesting[18:1,]))


# Test estimation and prediction

fit = fast_multinom(cbind(NO, I, VA, VG) ~ cancer_type + sample_id, data = small, refLevel=1, VC=F, subsetmatrix=NULL)

newdata = small[sample.int(nrow(small), 100),] 
pred = predict.fast_multinom(fit, newdata)

# Comparison to estimation with sample_id only and standard treatment contrasts

small.alt = small
contrasts(small.alt$sample_id) = contr.treatment(nlevels(small.alt$sample_id))
newdata.alt = newdata
contrasts(newdata.alt$sample_id) = contr.treatment(nlevels(small.alt$sample_id))

fit2 = fast_multinom(cbind(NO, I, VA, VG) ~ sample_id, data = small.alt, refLevel=1, VC=F, subsetmatrix=NULL)

pred2 = predict.fast_multinom(fit2, newdata.alt)

max(abs(pred - pred2))
# Nearly the same. 

MultinomialMutations/MultinomialMutations documentation built on May 22, 2019, 4:39 p.m.