R: Encode character variables into numeric

我的梦境 提交于 2020-01-29 23:28:52

问题


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" "AB" ...

How can I convert it to numeric variable so that "AA" would be coded as, e.g. 1, "AB" - as 2, etc.


回答1:


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



回答2:


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))


来源:https://stackoverflow.com/questions/29764983/r-encode-character-variables-into-numeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!