respect$BB6_cat5_0 <- ifelse(respect$BB6_cat5 == 1, 1, 0)
respect$BB6_cat5_1 <- ifelse(respect$BB6_cat5 == 2, 1, 0)
respect$BB6_cat5_2 <- ifelse(respect$BB6_cat5 == 3, 1, 0)
respect$BB6_cat5_3 <- ifelse(respect$BB6_cat5 == 4, 1, 0)
respect$BB6_cat5_4 <- ifelse(respect$BB6_cat5 == 5, 1, 0)
respect$J1A_cat2_0 <- ifelse(respect$J1A_cat2 == 1, 1, 0)
respect$J1A_cat2_1 <- ifelse(respect$J1A_cat2 == 2, 1, 0)
The category lengths vary for the variables and the naming of the dummy variables is very important for my project.
I have tried the following but this leaves out the referent variable due to how model.matrix works.
dummy.fun<-function(data) {
data_factor<-data.frame(lapply(data,as.factor))
names(data_factor)<-paste0(names(data_factor),'_')
data_all<-data.frame(model.matrix(~.+0,data=data_factor))
}
dummy.fun(respect)
However, this does not give me the BB6_cat5_0 unless it is the first variable in the dataset. Any ideas as top how I can get this function to output all dummy variables even the referents?