[R] sapply help

Milan Bouchet-Valat nalimilan at club.fr
Fri Feb 3 19:17:17 CET 2012


Le vendredi 03 février 2012 à 18:27 +0100, Ernest Adrogué a écrit :
> 3-02-2012, 08:37 (-0800); Filoche escriu:
> > Hi every one.
> > 
> > I'm learning how to use sapply (and other function of this family).
> > 
> > Here's what I'm trying to do.
> > 
> > I have a vector of lets say 5 elements. I also have a matrix of nX5. I would
> > like to know how many element by column are inferior to each element of my
> > vector.
> > 
> > On this example:
> > v = c(1:5)
> > M = matrix(3,2,5)
> > 
> > I would like to have a vector at the end which give me
> > 
> > 0 0 0 2 2
> > 
> 
> This does that:
> 
> > sapply(1:5, function(i) sum(M[,i] < v[i]))
> [1] 0 0 0 2 2
> 
> Basically, it's like a loop where at each iteration the function is
> called with one element of the vector 1:5 as argument, so what this
> really does is
> 
> sum(M[,1] < v[1]))
> sum(M[,2] < v[2]))
> ...
> 
> and then the results are put all together in a vector.
Though in your case, I think there are shorter solutions. For example:
> colSums(t(apply(M, 1, "<", v)))
[1] 0 0 0 2 2

apply() is more suited to matrices. Here, it takes each row separately,
and compares it with v. Then, you can just sum the result to count the
number of cases that fulfill the condition.


Cheers



More information about the R-help mailing list