Label Encoder functionality in R?

前端 未结 9 915
你的背包
你的背包 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:14

    df<- mtcars
    
    head(df)
    
    df$cyl  <- factor(df$cyl)
    
    df$carb <- factor(df$carb)
    vec <- sapply(df, is.factor)
    
    catlevels <- sapply(df[vec], levels)
    
    #store the levels for each category
    #level appearing first is coded as 1, second as 2 so on
    
    df <- sapply(df, as.numeric)
    
    class(df) #matrix
    
    df <- data.frame(df) 
    
    #converting back to dataframe
    
    head(df)
    

提交回复
热议问题