Label Encoder functionality in R?

前端 未结 9 928
你的背包
你的背包 2021-02-06 08:56

In python, scikit has a great function called LabelEncoder that maps categorical levels (strings) to integer representation.

Is there anything in R to do this?

9条回答
  •  心在旅途
    2021-02-06 09:29

    Create your vector of data:

    colors <- c("red", "red", "blue", "green")
    

    Create a factor:

    factors <- factor(colors)
    

    Convert the factor to numbers:

    as.numeric(factors)
    

    Output: (note that this is in alphabetical order)

    # [1] 3 3 1 2
    

    You can also set a custom numbering system: (note that the output now follows the "rainbow color order" that I defined)

    rainbow <- c("red","orange","yellow","green","blue","purple")
    ordered <- factor(colors, levels = rainbow)
    as.numeric(ordered)
    # [1] 1 1 5 4
    

    See ?factor.

提交回复
热议问题