Quantiles by factor levels in R

前端 未结 2 1161
梦毁少年i
梦毁少年i 2020-12-18 04:07

I have a data frame and I\'m trying to create a new variable in the data frame that has the quantiles of a continuous variable var1, for each level of a factor

2条回答
  •  心在旅途
    2020-12-18 04:28

    Use ave on your dat data frame. Full example with your simulated data and qfun function:

    # some data
    set.seed(472)
    dat <- data.frame(var1 = rnorm(50, 10, 3)^2,
                  strata = factor(sample(LETTERS[1:5], size = 50, replace = TRUE))
                  )
    
    # function to get quantiles
    qfun <- function(x, q = 5) {
        quantile <- cut(x, breaks = quantile(x, probs = 0:q/q), 
            include.lowest = TRUE, labels = 1:q)
        quantile
    }
    

    And my addition...

    dat$q <- ave(dat$var1,dat$strata,FUN=qfun)
    

提交回复
热议问题