简体   繁体   English

是否有将分类变量转换为连续变量的 R function?

[英]Is there an R function which converts categorical variables into continuous variables?

My dataframe is of the following form:我的 dataframe 具有以下形式:

Index: Number of pets owned: Age range指数:拥有的宠物数量:年龄范围

  1. 10: 30s 10:30秒

  2. 2: 50s 2:50秒

  3. 4: 60s 4:60年代

  4. 6: <20s 6:<20s

  5. 9: 70s 9:70年代

etc. Essentially, the number of age ranges are <20s, 20s, 30s, 40s, 50s, 60s, 70s.等等。基本上,年龄范围的数量是<20s、20s、30s、40s、50s、60s、70s。 What I would like to do is turn this categorical age range variable into a continuous one by assigning 1, 2, 3, 4, 5, 6, 7 to the age ranges.我想做的是通过将 1、2、3、4、5、6、7 分配给年龄范围,将这个分类年龄范围变量变成一个连续变量。 Any idea how I can do this in R?知道如何在 R 中做到这一点吗? I think the as.numeric function could be useful but I've never used it before.我认为 as.numeric function 可能很有用,但我以前从未使用过它。

You can do that using as.numeric() function.你可以使用as.numeric() function 来做到这一点。 Using your dataframe we have:使用您的 dataframe 我们有:

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

This is your Dataframe looks like:这是你的 Dataframe 看起来像:

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

Checking the class data type of age_rank column we have:检查 age_rank 列的 class 数据类型,我们有:

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

So using as.numeric() :所以使用as.numeric()

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

This is your dataframe with the values 1, 2, 3, 4, 5 in the age rank.这是您的 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.

Checking the column again:再次检查该列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM