[英]How to create a continuous variable from a categorical variable
我有關於個人上課年齡的信息。 我的目標是將這些信息轉換為在每個類中具有相等分布的連續變量“年齡”。 我如何在R中做到這一點?
Class_age
20-22
20-22
20-22
23-25
23-25
23-25
23-25
23-25
20-22
20-22
這將在每個組的最大值和最小值之間均勻采樣,並返回與原始數據幀相同數量的值:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.