【问题标题】:How to create a continuous variable from a categorical variable如何从分类变量创建连续变量
【发布时间】:2015-04-24 16:45:59
【问题描述】:

我有关于班级中个人年龄的信息。我的目标是将这些信息转换为连续变量“年龄”,并在每个类别中平均分布。我如何在 R 中做到这一点?

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

【问题讨论】:

    标签: r variables categorical-data


    【解决方案1】:

    这在每个组内的最小值和最大值之间均匀采样,返回与原始数据帧相同数量的值:

    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)
    })
    

    示例输出:

       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
    

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多