I need to convert categorical variables into multiple dichotomous ("dummy") variables to use in a logistic regression. Say my data frame is:
tdf <- data.frame(first=sample(c("A", "B", "C", "D"), 100, replace=T),
lobe = sample(c("RUL", "RML", "RLL", "LUL", "LLL"), 100, replace=T),
continuous=sample(1:100, 100),
smoker = sample(c("never", "less20", "more20"), 100, replace=T)
)
I could manually do
first. <- with (tdf, factor (first))
dummies <- model.matrix(~ first.)
dummies <- dummies[,-1]
tdf <- cbind(tdf, dummies)
Note that it is important to call the factor "first." (or more generally, "variable.") because the dummy variables will inherit this prefix into their respective names, making it easier to identify them later ('variable1.factor2', 'variable1.factor3' etc).
My question is: How can do this using a function that would programatically assign variable names:
dummify <- function(df, vectorOfColIndices) {
cn <- colnames(df)
for (i in vectorOfColIndices) {
t. <- with (tdf, factor (df[i])) # temporary factor
assign (cn[i], t.) # give it the proper 'Variable.' name
dummies <- model.matrix(~ ????) # Stuck here: how do I call this newly created structure?
...
}
}
So that I can later transform a data frame like this:
vd <- c(1,2,4) # columns that need to be converted into dummy vars
df <- dummify(df, vd)
?reformulate... - Ben Bolker