用因子替换范围内的数字

时间:2012-04-19 06:08:23

标签: r data-processing r-factor

给定一个数据帧列是一系列整数(年龄),我想将整数范围转换为有序变量。

我目前的代码不起作用,我该怎么做?

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)

1 个答案:

答案 0 :(得分:16)

使用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 ...