我的数据格式如下:
指数:养宠物数量:年龄范围
H 210G 211基本上,年龄范围是<20岁、20岁、30岁、40岁、50岁、60岁、70岁。我想要做的是通过给年龄范围分配1、2、3、4、5、6、7,将这个分类年龄范围变量转换为一个连续的变量。知道我怎么能在R里做到这一点吗?我认为as.numeric函数可能很有用,但我以前从未使用过它。
发布于 2021-11-27 04:03:58
您可以使用as.numeric()函数来完成这一任务。利用你的数据,我们有:
data_frame <- data.frame(
pets_owned = c("10", "2", "4","6","9"),
age_rank = c("30", "50", "60","20","70")
)这是您的Dataframe看起来:
> 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"https://stackoverflow.com/questions/62475876
复制相似问题