簡體   English   中英

用因子替換范圍內的數字

[英]Replacing numbers within a range with a 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)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM