Replacing numbers within a range with a factor

大城市里の小女人 提交于 2019-11-26 06:49:32

问题


Given a dataframe column which is a series of integers (age), I want to convert ranges of integers into ordinal variables.

My current code doesn\'t work, how do I do this?

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:


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


来源:https://stackoverflow.com/questions/10222525/replacing-numbers-within-a-range-with-a-factor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!