Categorical covariates in Cox model in R When there are multiple levels in a variable (ex. 1,2,3,4), should I use as.factor() to transform it to a factor when I fit a cox model in R?
When there are only two levels (ex. 1 for male and 2 for female), the results are the same. But when there are more than 2 levels, using as.factor or not makes the results different.
Should I use as.factor() here?
I would be very appreciated if someone could answer this question.
 A: Numbers are often used to mark the different levels of a categorical predictor variable, either explicitly by the investigator or implicitly by the software. If the software interprets those numbers as numbers instead of as labels for categories by the software, the categorical variable will be treated as if it were a continuous numeric variable.
If the levels have a natural ordering, for example Stages I through IV of a particular type of cancer, you have what's called an ordinal predictor. If the software interprets that as a numeric variable, it assumes equal associations with outcome between successive levels of the predictor. In some cases that assumption might be close to true, as you might find with cancer Stage labeled 1 through 4 and treated as numeric. In that situation you might miss the mis-interpretation of Stage by the software, unless you notice that you are only getting 1 coefficient for Stage instead of the 3 coefficients you should be getting for differences from the reference for each of the other levels.
If the levels have no natural ordering, say different types of cancer, then results with more than 2 levels of an unordered categorical predictor variable coded as numbers and treated as numeric will bear no necessary relation to reality. Results might differ dramatically depending on the assignment of the numeric labels to the levels, as you found.
If you are assigning the numbers yourself to the levels, make sure that the software interprets them either as ordinal indicators or as labels, and not as numbers. If your software allows (as R does), it can be less confusing and make outputs easier to interpret if you use character strings as names for levels of an unordered categorical variable (or, if appropriate, specify a categorical predictor as ordinal), and let the software handle the rest.
