用因子替换范围内的数字 [英] Replacing numbers within a range with a factor

查看:64
本文介绍了用因子替换范围内的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

使用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 参数来重新标记级别:

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

这篇关于用因子替换范围内的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆