[R] Recoding lists of categories of a variable

Bert Gunter bgunter.4567 at gmail.com
Tue Oct 11 05:49:02 CEST 2016

Still overkill, I believe.

" Unlike using the numeric levels, that doesn't fail if some of the
levels I expect are absent; it only fails (and does so visibly) when
there's a value in there that I haven't assigned a coding to. So it's
a tad more robust. "

If you are concerned about missing levels -- which I agree is
legitimate -- then the following simple modification works (for
**factors** of course):

> d <- factor(letters[1:2],levels= letters[1:3])
> d
[1] a b
Levels: a b c
> f <- factor(d,levels = levels(d), labels = LETTERS[3:1])
> f
[1] C B
Levels: C B A

## No levels lost !

Does that allay your concerns?


More information about the R-help mailing list