Percentile for Each Observation w/r/t Grouping Variable

后端 未结 7 1234
广开言路
广开言路 2021-02-06 10:39

I have some data that looks like the following. It is grouped by variable \"Year\" and I want to extract the percentiles of each observation of Score, with respect to t

7条回答
  •  时光说笑
    2021-02-06 11:19

    How about something like:

    Year <- c(2000,2008,2008,2000,2000)
    Fees <- c(1000,1050,2000,1700,2000)
    dat <- data.frame(Fees,Year,result=NA)
    res <- tapply(Fees,Year,function(x) rank(x,ties.method="max")/length(x))
    for(i in 1:length(res))
       dat[Year==as.numeric(names(res)[i]),"result"] <-res[[i]]
    

    which yields:

      Fees Year    result
    1 1000 2000 0.3333333
    2 1050 2008 0.5000000
    3 2000 2008 1.0000000
    4 1700 2000 0.6666667
    5 2000 2000 1.0000000
    

提交回复
热议问题