[英]How to convert factor ordered variables to numeric
我有一个包含79个解释变量的数据集,其中43个是因子。
一些因子变量只是通用标签-对于那些我打算使用虚拟变量进行数字表示的标签。
因素变量的其他一些子集包含有序的级别,例如:
BsmtQual: Evaluates the height of the basement
Ex Excellent (100+ inches)
Gd Good (90-99 inches)
TA Typical (80-89 inches)
Fa Fair (70-79 inches)
Po Poor (<70 inches
NA No Basement
我想将这样的因子变量转换为数值,该数值将保留从最低到最高的级别顺序,这意味着在操作之后,我想得到类似以下内容:
BsmtQual: Evaluates the height of the basement
Ex records will be replaced with: 6
Gd records will be replaced with: 5
TA records will be replaced with: 4
Fa records will be replaced with: 3
Po records will be replaced with: 2
NA records will be replaced with: 1
(请注意,如果我可以将NA替换为0-因为NA实际上并不指代该变量的缺失数据,而是指的是具有较低基础得分的记录)
如何编写替换代码?
req_var$ExterQual <- revalue(req_var$ExterQual, c("Ex"=5 ,"Gd"=4 , "TA"=3 , "Fa"=2 ,"Po"=1))
在这里,我将不考虑这些数据集中的NA。 如果要将数字NA设置为0,则在上述命令中添加“ NA” = 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.