R: Mapping table of levels and labels of factor variable

后端 未结 1 1024
陌清茗
陌清茗 2020-12-21 23:06

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

相关标签:
1条回答
  • 2020-12-21 23:42

    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
    
    0 讨论(0)
提交回复
热议问题