R: Encode character variables into numeric

前端 未结 2 2016
无人及你
无人及你 2021-01-14 11:18

In R code I have a character variable var that has values \"AA\", \"AB\", \"AC\", etc.

str(var)
chr [1:17003] \"AA\" \"AA\" \"AA\" \"AA\" \"AB\"         


        
相关标签:
2条回答
  • 2021-01-14 11:53

    you can use them by directly converting them into factors with labeling.

    x$Country = factor(x$Country,
                   levels = c('AA', 'AB', 'AC'),
                   labels = c(1, 2, 3))
    
    0 讨论(0)
  • 2021-01-14 11:54

    You can convert the string to a factor and then to numeric.

    x <- c("AA", "AB", "AB", "AC", "AA", "XY")
    as.numeric(as.factor(x))
    # [1] 1 2 2 3 1 4
    

    Alternatively, you can use match and unique:

    match(x, unique(x))
    # [1] 1 2 2 3 1 4
    
    0 讨论(0)
提交回复
热议问题