这个问题在这里已经有了答案:
Convert continuous numeric values to discrete categories defined by intervals
(2 个回答)
去年关闭。
给定一个数据框列,它是一系列整数(年龄),我想将整数范围转换为序数变量。
我当前的代码不起作用,我该怎么做?
df <- read.table("http://dl.dropbox.com/u/822467/df.csv", header = TRUE, sep = ",")
df[(df >= 0) & (df <= 14)] <- "Age1"
df[(df >= 15) & (df <= 44)] <- "Age2"
df[(df >= 45) & (df <= 64)] <- "Age3"
df[(df > 64)] <- "Age4"
table(df)
最佳答案
使用 cut
一步完成:
dfc <- cut(df$x, breaks=c(0, 15, 45, 56, Inf))
str(dfc)
Factor w/ 4 levels "(0,15]","(15,45]",..: 3 4 3 2 2 4 2 2 4 4 ...
一旦您满意,
breaks
正确指定,然后您也可以使用 labels
重新标记级别的参数:dfc <- cut(df$x, breaks=c(0, 15, 45, 56, Inf), labels=paste("Age", 1:4, sep=""))
str(dfc)
Factor w/ 4 levels "Age1","Age2",..: 3 4 3 2 2 4 2 2 4 4 ...
关于用因子替换范围内的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222525/