[R] counts in quantiles in and from a matrix

Dennis Murphy djmuser at gmail.com
Thu Oct 6 05:18:19 CEST 2011


Hi:

Here's one way:

m <- matrix(rpois(100, 8), nrow = 5)
f <- function(x) {
    q <- quantile(x, c(0.1, 0.9), na.rm = TRUE)
    c(sum(x < q[1]), sum(x > q[2]))
    }

t(apply(m, 1, f))

HTH,
Dennis

On Wed, Oct 5, 2011 at 8:11 PM, Ben qant <ccquant at gmail.com> wrote:
> Hello,
>
> I'm trying to get the count of values in each row that are above and below
> quantile thresholds. Thanks!
>
> Example:
>
>> x = matrix(1:30,5,6)
>> x
>     [,1] [,2] [,3] [,4] [,5] [,6]
> [1,]    1    6   11   16   21   26
> [2,]    2    7   12   17   22   27
> [3,]    3    8   13   18   23   28
> [4,]    4    9   14   19   24   29
> [5,]    5   10   15   20   25   30
>> qtl = t(apply(x, 1, quantile, probs = c(.1,.9),na.rm=T))
>> qtl
>     10%  90%
> [1,] 3.5 23.5
> [2,] 4.5 24.5
> [3,] 5.5 25.5
> [4,] 6.5 26.5
> [5,] 7.5 27.5
>
> I would like counts like this for each row:
>
> cnts
>    [,1] [,2]
> [1,]   1    1
> [2,]   1    1
> [3,]   1    1
> [4,]   1    1
> [5,]   1    1
>
> ...because for the first row (x[1,]) only value 1 is less than 3.5 and only
> value 26 is greater 23.5 and so on for the other rows. I'm thinking its a
> apply(x,1,...some FUN here...), but still getting use to apply and I've been
> coding for too long...
>
> Also, if anyone knows how to change the background color of the r-Tinn
> editor my eyes would love you!  Off to bed. I look forward to your answers!
>
> Thanks!
>
> Ben
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list