如何将可枚举字符串向量转换为数字向量?

机器算法验证 r
2022-03-15 04:39:59

如何将下面的x转换为像y这样的向量?

x <- ["a", "b", "b", "c", ...]

y <- [1, 2, 2, 3, ...]

更新:

我最终得到:

levels(x) <- 1:length(levels(x))
4个回答

这是一种可能性,与@Roman Lustrik 非常相似,但更自动化一点。

比如说

x <- c("a", "b", "b", "c")

然后

   > x <- as.factor(x)
   > levels(x) <- 1:length(levels(x))
   > x <- as.numeric(x)

完成这项工作:

   > print(x)
   [1] 1 2 2 3

另一个编程问题偷偷摸摸...

无论如何,更快的方法是

unclass(factor(x))

另外,也可以添加levels(...)<-NULL以删除冗余属性(脚本中不需要太多)。

有几种方法可以做到这一点。这是一个。

> (a <- as.factor(sample(letters[1:5], 30, replace = TRUE)))
    [1] d a e e e c b e b b c a d d d d c b c c b b e b e b c d c b
    Levels: a b c d e
> (levels(a) <- 1:5)
    [1] 1 2 3 4 5
> a <- as.numeric(a) # convert these factors into numbers
as.numeric(factor(c("d", "a", "b", "b", "c")))

[1] 4 1 2 2 3