Convert categorical variables to numeric in R

You can use unclass() to display numeric values of factor variables :

Type_peau<-as.factor(c("Mixte","Normale","Sèche","Mixte","Normale","Mixte"))
Type_peau
unclass(Type_peau)

To do so on all categorical variables, you can use sapply() :

must_convert<-sapply(M,is.factor)       # logical vector telling if a variable needs to be displayed as numeric
M2<-sapply(M[,must_convert],unclass)    # data.frame of all categorical variables now displayed as numeric
out<-cbind(M[,!must_convert],M2)        # complete data.frame with all variables put together

EDIT : A5C1D2H2I1M1N2O1R2T1’s solution works in one step :

out<-data.matrix(M)

It only works if your data.frame doesn’t contain any character variable though (otherwise, they’ll be put to NA).

Leave a Comment