首页 > 解决方案 > 是否有将分类变量转换为连续变量的 R 函数?

问题描述

我的数据框具有以下形式:

指数:拥有的宠物数量:年龄范围

  1. 10 : 30 秒

  2. 2 : 50 秒

  3. 4 : 60 秒

  4. 6 : <20s

  5. 9 : 70 年代

等等。基本上,年龄范围的数量是<20s、20s、30s、40s、50s、60s、70s。我想做的是通过将 1、2、3、4、5、6、7 分配给年龄范围,将这个分类年龄范围变量变成一个连续变量。知道如何在 R 中做到这一点吗?我认为 as.numeric 函数可能很有用,但我以前从未使用过它。

标签: rdataframecategorical-datacontinuous

解决方案


你可以使用as.numeric()函数来做到这一点。使用您的数据框,我们有:

data_frame <- data.frame(
pets_owned = c("10", "2", "4","6","9"),
age_rank = c("30", "50", "60","20","70")
)

这是您的数据框的样子:

> data_frame
  pets_owned age_rank
1         10       30
2          2       50
3          4       60
4          6       20
5          9       70

检查我们拥有的 age_rank 列的类数据类型:

> class(data_frame$age_rank)
[1] "factor"

所以使用as.numeric()

data_frame[2]=as.numeric(data_frame$age_rank)
# update the value in the position [2] of the dataframe

这是您的数据框,年龄等级中的值为 1、2、3、4、5。

> data_frame
  pets_owned age_rank
1         10        2
2          2        3
3          4        4
4          6        1 # note that the value 1 
5          9        5 # correspond with the age of 20.

再次检查该列:

> class(data_frame$age_rank)
[1] "numeric"

推荐阅读