DescTools (version 0.99.18)

Dummy: Generate Dummy Codes for a Factor

Description

Generates a matrix of dummy codes (class indicators) for a given factor.

Usage

Dummy(x, method = c("treatment", "sum", "helmert", "poly", "full"), base = 1)

Arguments

x
factor or vector of classes for cases.

method
defines the method of the contrasts being formed. Can be one out of "treatment", "sum", "helmert", "poly", "full", whereas "treatment" is the default one. Abbreviations are accepted. The option "full" returns a full set of class indicators, say a dummy factor for EACH level of x. Note that this would be redundant for lm and friends!

base
an integer specifying which group is considered the baseline group.

Value

The rows correspond to the number of elements in x and the columns to it's levels.

References

Venables, W N and Ripley, B D (2002): Modern Applied Statistics with S. Fourth edition. Springer.

See Also

model.frame, contrasts, class.ind in the package nnet

Examples

Run this code
x <- c("red","blue","green","blue","green","red","red","blue") 
Dummy(x) 
Dummy(x, base = 2)

Dummy(x, method = "sum")


y <- c("Max","Max","Max","Max","Max","Bill","Bill","Bill")

Dummy(y) 
Dummy(y, base = "Max")

Dummy(y, base = "Max", method="full")


# "Undummy" (revert the dummy coding) 
m <- Dummy(y, method="full")
m
z <- apply(m, 1, function(x) colnames(m)[x==1])
z
identical(y, as.vector(z))

m <- Dummy(y)
m
z <- apply(m, 1, function(x) ifelse(sum(x)==0, attr(m,"base"), colnames(m)[x==1]))
z

Run the code above in your browser using DataCamp Workspace