简体   繁体   中英

How to create a continuous variable from a categorical variable

I have an information on age of individuals in classes. My aim is to convert this information in a continuous variable "Age" with equal distribution within each class. How can I do it in R?

Class_age
20-22
20-22
20-22
23-25
23-25
23-25
23-25
23-25
20-22
20-22

This samples uniformly between the minimum and maximum within each group, returning the same number of values as your original dataframe:

df = read.table(file='clipboard', header=TRUE)

library(plyr)
ddply(df, .(Class_age), function(x) {
    level = x$Class_age[1]
    min_max = as.numeric(strsplit(as.character(level), '-')[[1]])
    x$age = runif(nrow(x), min=min_max[1], max=min_max[2])
    return(x)
})

Example output:

   Class_age      age
1      20-22 21.08586
2      20-22 21.78266
3      20-22 21.11404
4      20-22 20.46550
5      20-22 21.01637
6      23-25 24.52937
7      23-25 24.71782
8      23-25 23.26885
9      23-25 23.69933
10     23-25 24.61314

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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