splitting a continuous variable into groups of equal number of elements - return numeric vector from bin values

前端 未结 2 1556
不知归路
不知归路 2021-01-27 08:36

I have a continuous variable that I want to split into bins, returning a numeric vector (of length equal to my original vector) whose values relate to the values of the bins. E

2条回答
  •  情话喂你
    2021-01-27 09:16

    Use ave like this:

    Given:

    x = c(1,5,3,12,5,6,7)
    

    Mean:

    ave(x,cut2(x,g = 3), FUN = mean)
    [1] 3.5 3.5 3.5 9.5 3.5 6.0 9.5
    

    Min:

    ave(x,cut2(x,g = 3), FUN = min)
    [1] 1 1 1 7 1 6 7
    

    Max:

    ave(x,cut2(x,g = 3), FUN = max)
    [1]  5  5  5 12  5  6 12
    

    Or standard deviation:

    ave(x,cut2(x,g = 3), FUN = sd)
    [1] 1.914854 1.914854 1.914854 3.535534 1.914854       NA 3.535534
    

    Note the NA result for only one data point in interval.

    Hope this is what you need.

    NOTE:
    Parameter g in cut2 is number of quantile groups. Groups might not have the same amount of data points, and the intervals might not have the same length.
    On the other hand, cut splits the interval into several of equal length.

提交回复
热议问题