Most R functions used in econometrics convert factor variables into a set of dummy/binary variables automatically. This is useful when estimating a linear model, saving the user from the laborious activity of manually including the dummy variables as regressors. However, what if you want to reshape your dataframe so that it contains such dummy variables?
The following function, datdum(.), is a simple workaround. The first argument is the factor variable (which can also be a character), the second is the dataframe and the third is the name you want to call these dummy variables.
datdum <- function(x, data, name){
data$rv <- rnorm(dim(data)[1],1,1)
mm <- data.frame(model.matrix(lm(data$rv~-1+factor(data[,x]))))
names(mm) <- paste(name,1:dim(mm)[2],sep=".")
data$rv <- NULL
data <- cbind(data,mm)
return(data)
}
# simple example
dat <- c("A","B","C")
dat <- data.frame(dat)
datdum(x="dat",data=dat,name="category")
#########################
# output
#########################
> dat
dat
1 A
2 B
3 C
> datdum(x="dat",data=dat,name="category")
dat category.1 category.2 category.3
1 A 1 0 0
2 B 0 1 0
3 C 0 0 1
This is just a roundabout way to get the contrasts matrix for a factor. Assuming you are using treatment contrasts (the default), here is a version of datdum() that calls contr.treatment() directly. It also uses x as the default value for name.
datdum <- function(x, data, name=x){
mm <- data.frame(contr.treatment(length(levels(factor(data[,x]))), contrasts=FALSE))
names(mm) <- paste(name,1:ncol(mm),sep=".")
data <- cbind(data,mm)
return(data)
}
There’s also the dummies package on CRAN.
require(dummies)
dummy(dat$dat)
From what I can see this has been removed from CRAN.