r - 是否有将分类变量转换为连续变量的 R 函数?
问题描述
我的数据框具有以下形式:
指数:拥有的宠物数量:年龄范围
10 : 30 秒
2 : 50 秒
4 : 60 秒
6 : <20s
9 : 70 年代
等等。基本上,年龄范围的数量是<20s、20s、30s、40s、50s、60s、70s。我想做的是通过将 1、2、3、4、5、6、7 分配给年龄范围,将这个分类年龄范围变量变成一个连续变量。知道如何在 R 中做到这一点吗?我认为 as.numeric 函数可能很有用,但我以前从未使用过它。
解决方案
你可以使用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"
推荐阅读
- sharepoint - 在 SharePoint 中创建文件夹并使用 REST API 在 1 个事务中配置权限
- javascript - 如果 prop 发生更改,是否可以在重新渲染组件之前通过 this.props 访问此更改?
- git - 重新同步编辑过的 Flutter 源文件
- java - Spring Boot JPA 空指针异常
- robotics - 车杆倒立摆任务如何选择奖励函数
- ios - Flutter 中的 iOS 分段控件
- string - Julia - 检查字符串中的每个字符是小写还是空格
- swift - type A 要求 type B 是一个类类型 swift 4
- apache-spark - 群组成员支持的协议与现有成员的协议不兼容
- tensorflow - 如何使用 tf 会话根据网络输出更新游戏状态以进行强化学习