Skip to content
Prev 312515 / 398506 Next

subgroup-based quantiles

Hi,
You could also try ?ave()
dat$Age_group<-ave(dat$Age,dat$GENDER,FUN=function(x){cut(x,labels=1:10,breaks=quantile(x,seq(0,1,.1)),include.lowest=TRUE)})
?dat
#? GENDER Age Age_group
#1????? 2? 45???????? 1
#2????? 1? 58??????? 10
#3????? 1? 54???????? 1
#4????? 2? 71??????? 10
#5????? 2? 64???????? 5
A.K.



----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: R Kozarski <r.kozarski at gmail.com>
Cc: r-help at r-project.org
Sent: Friday, November 30, 2012 1:07 PM
Subject: Re: [R] subgroup-based quantiles

Hello,

If you want Age quantiles by gender, you have to split the data by 
gender, apply the same code then recombine the result.


fun <- function(x){
? ?  Age_group <- cut(x[, "Age"], labels=c(1:10),
? ? ? ?  breaks=quantile(x[, "Age"], seq(0,1,.1)),
? ? ? ?  include.lowest = TRUE)
? ?  cbind(x, Age_group)
}

result <- do.call(rbind, lapply(split(dat, dat[, "GENDER"]), fun))
rownames(result) <- seq_len(nrow(result))
result


Hope this helps,

Rui Barradas
Em 30-11-2012 12:18, R Kozarski escreveu:
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.