I am pretty sure I am missing something here, but how can I get a mapping table of the integer codes and the labels of a factor variable in R?
For example, in the chickwts
dataset, I would like the output for the feed
variable
1 --> casein
2 --> horsebean
3 --> linseed
4 --> meatmeal
5 --> soybean
6 --> sunflower
I am pretty sure there is a built-in function for this, but I can't find it, and neither levels
, nlevels
or unclass
gives me what I want.
Any suggestions?
The codes are just the index into the levels(...)
vector.
with(chickwts,data.frame(code=seq_along(levels(feed)),levels=levels(feed)))
# code levels
# 1 1 casein
# 2 2 horsebean
# 3 3 linseed
# 4 4 meatmeal
# 5 5 soybean
# 6 6 sunflower
This is the same result you get with as.integer(...)
.
with(chickwts,data.frame(code=as.numeric(unique(feed)),level=unique(feed)))
# code level
# 1 2 horsebean
# 2 3 linseed
# 3 5 soybean
# 4 6 sunflower
# 5 4 meatmeal
# 6 1 casein
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.