#' Convert a single variable of multiple levels into binary dummy variables
#'
#' \code{dummy(dataframe,variable,drop=NULL)}
#'
#' @param dataframe name of the data frame
#' @param variable either the name of the variable in inverted commas or column index
#' @param abbrev logical whether the factor levels should be abbreviated too
#'
#' @details Will convert a variable with n levels to n dummy variables
#' appended as columns to the data frame, each comprising 0s and 1s. The variable
#' can be passed as either the name of the variable in inverted commas or the column
#' number. The new variable names will be an abbreviated form of the original
#' variable with an underscore and then the suffix of the original factor level
#' (with the option to abbreviate). One of the levels may not be required in, say,
#' a linear model since it will be represented by the intercept.
#'
#' @examples
#' dummy(mtcars[,1:2],"cyl")
dummy = function(dataframe, variable, abbrev=TRUE){
NC = ncol(dataframe)
Name = colnames(dataframe[variable])
V = as.factor(dataframe[,variable])
if(abbrev==TRUE)V = as.factor(abbreviate(V))
Lvls = levels(V)
Len = length(Lvls)
for(a in 1:Len){
X = ifelse(V==levels(V)[a],1,0)
dataframe=cbind(dataframe,as.integer(X))
colnames(dataframe)[NC+a]=paste(abbreviate(Name,minlength = 4),
levels(V)[a],sep = "_")
}
return(dataframe)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.