将分类变量转换为 R 中的因子时出错
Error in converting categorical variables to factor in R
在这个 tutorial 中,我尝试使用另一种方法将分类变量转换为因子。
文章中使用了以下方法
library(MASS)
library(rpart)
cols <- c('low', 'race', 'smoke', 'ht', 'ui')
birthwt[cols] <- lapply(birthwt[cols], as.factor)
并且我将最后一行替换为
birthwt[cols] <- as.factor((birthwt[cols]))
但结果是 NA all
这有什么问题?
as.factor((birthwt[cols]))
在 5 个向量的列表上调用 as.factor
。如果你这样做,R 会将这 5 个向量中的每一个解释为因子变量的水平,并将列 headers 解释为标签,这显然不是你想要的:
> as.factor(birthwt[cols])
low race smoke ht ui
<NA> <NA> <NA> <NA> <NA>
5 Levels: c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) ...
> labels(as.factor(birthwt[cols]))
[1] "low" "race" "smoke" "ht" "ui"
lapply
遍历列表,分别对该列表中的每个向量调用函数 as.factor
。您需要这样做以将每个变量分别转换为一个因子,而不是试图将整个列表转换为一个因子,这就是 as.factor(birthwt[cols])
所做的。
在这个 tutorial 中,我尝试使用另一种方法将分类变量转换为因子。
文章中使用了以下方法
library(MASS)
library(rpart)
cols <- c('low', 'race', 'smoke', 'ht', 'ui')
birthwt[cols] <- lapply(birthwt[cols], as.factor)
并且我将最后一行替换为
birthwt[cols] <- as.factor((birthwt[cols]))
但结果是 NA all
这有什么问题?
as.factor((birthwt[cols]))
在 5 个向量的列表上调用 as.factor
。如果你这样做,R 会将这 5 个向量中的每一个解释为因子变量的水平,并将列 headers 解释为标签,这显然不是你想要的:
> as.factor(birthwt[cols])
low race smoke ht ui
<NA> <NA> <NA> <NA> <NA>
5 Levels: c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) ...
> labels(as.factor(birthwt[cols]))
[1] "low" "race" "smoke" "ht" "ui"
lapply
遍历列表,分别对该列表中的每个向量调用函数 as.factor
。您需要这样做以将每个变量分别转换为一个因子,而不是试图将整个列表转换为一个因子,这就是 as.factor(birthwt[cols])
所做的。