Learn R Programming

quest (version 0.2.0)

nom2dum: Nominal Variable to Dummy Variables

Description

nom2dum converts a nominal variable into a set of dummy variables. There is one dummy variable for each unique value in the nominal variable. Note, base R does this recoding internally through the model.matrix.default function, but it is used in the context of regression-like models and it is not clear how to simplify it for general use cases outside that context.

Usage

nom2dum(nom, yes = 1L, no = 0L, prefix = "", rtn.fct = FALSE)

Value

data.frame of dummy columns with colnames specified by

paste0(prefix, unique(nom)) and rownames specified by

names(nom) or default data.frame rownames (i.e., c("1","2","3", etc.) if names(nom) is NULL.

Arguments

nom

character vector (or any atomic vector, including factors, which will be then coerced to a character vector) specifying the nominal variable.

yes

atomic vector of length 1 specifying what unique value should represent rows when the nominal category of interest is present. For a traditional dummy variable this value would be 1.

no

atomic vector of length 1 specifying what unique value should represent rows when the nominal category of interest is absent. For a traditional dummy variable this value would be 0.

prefix

character vector of length 1 specifying the string that should be appended to the beginning of each colname in the return object.

rtn.fct

logical vector of length 1 specifying whether the columns of the return object should be factors where the first level is no and the second level is yes.

Details

Note, that yes and no are assumed to be the same typeof. If they are not, then the columns in the return object will be coerced to the most complex typeof (i.e., most to least: character, double, integer, logical).

See Also

Examples

Run this code
nom2dum(infert$"education") # default
nom2dum(infert$"education", prefix = "edu_") # use of the `prefix` argument
nom2dum(nom = infert$"education", yes = "one", no = "zero",
   rtn.fct = TRUE) # returns factor columns

Run the code above in your browser using DataLab