TYL
TYL

Reputation: 1637

r: finding the level values for factors in a variable

I need help in finding out the values for the levels of a variable. For example,

    therapy$type <- factor(therapy$type, levels = c(1: 3), labels = c("cbt", "ipt", "control"))

Assuming I forgot about the levels (the numbers assigned to them) for each of the type of therapy, how do I find them? Result should be tell me something like cbt = 1, ipt = 2, control = 3

Upvotes: 1

Views: 546

Answers (1)

shadowtalker
shadowtalker

Reputation: 13913

If you are 100% sure that you used levels = 1:3, you can just write levels(therapy$type), and the labels will be printed in the original order. So you can just use the index of the resulting vector to tell you the original levels.

However, if you did something like levels = 9:11, there's no way to tell. The levels argument in the factor function is not saved anywhere. I personally think this is an oversight in the language, and that factors ought to save a mapping between their original levels and the current labels/levels when created with factor.

Upvotes: 2

Related Questions