如何在R中将数值表示的因子转换为整数或数值变量?

我们可以通过使用as.numeric函数定义因子的级别或定义因子的字符,将因子转换为整数或数字变量

示例

> f <- factor(sample(runif(10), 10, replace = TRUE))
> f
[1] 0.323049098020419 0.916131897130981 0.271536672720686 0.462429489241913
[5] 0.657008627429605 0.462429489241913 0.462429489241913 0.212830029195175
[9] 0.271536672720686 0.497305172728375
7 Levels: 0.212830029195175 0.271536672720686 ... 0.916131897130981

使用数字

> as.numeric(levels(f))[f]
[1] 0.3230491 0.9161319 0.2715367 0.4624295 0.6570086 0.4624295 0.4624295
[8] 0.2128300 0.2715367 0.4973052
> Using as.numeric(as.character( ))
> as.numeric(as.character(f))
[1] 0.3230491 0.9161319 0.2715367 0.4624295 0.6570086 0.4624295 0.4624295
[8] 0.2128300 0.2715367 0.4973052