Replacing numbers within a range with a factor

2019-01-08 01:44发布

As above. The dataframe is a series of integers which are age. I am trying to convert them into ordinal variables. The code is below.

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)

As we can see this doesn't work. Can anyone help me propose a better way to do this?

1条回答
祖国的老花朵
2楼-- · 2019-01-08 02:18

Use cut to do this in one step:

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

Once you are satisfied that the breaks are correctly specified, you can then also use the labels argument to relabel the levels:

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 ...
查看更多
登录 后发表回答