From the many answers I could read, the only given way was to expand the number of variables according to the number of factors. If you have a variable "pet" with levels "dog" and "cat", you would end up with pet_dog and pet_cat.
In my case I wanted to stay with the same number of variables, by just translating the factor variable to a numeric one, in a way that can applied to many variables with many levels, so that cat=1 and dog=0 for instance.
Please find the corresponding solution below:
crime <- data.frame(city = c("SF", "SF", "NYC"),
year = c(1990, 2000, 1990),
crime = 1:3)
indx <- sapply(crime, is.factor)
crime[indx] <- lapply(crime[indx], function(x){
listOri <- unique(x)
listMod <- seq_along(listOri)
res <- factor(x, levels=listOri)
res <- as.numeric(res)
return(res)
}
)