[This article was first published on DiffusePrioR » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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
To leave a comment for the author, please follow the link and comment on their blog: DiffusePrioR » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.