Skip to content
Prev 359770 / 398503 Next

apply mean function to a subset of data

Here are several ways to get there, but your original loop is fine once it is corrected:
[1] 0.271489 1.117015

Using sapply() to hide the loop:
[1] 0.271489 1.117015

Or use head()
[1] 0.271489 1.117015

Or mapply() instead of sapply
1        2 
0.271489 1.117015

------------------------------
David L. Carlson
Department of Anthropology
Texas A&M University

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Jim Lemon
Sent: Saturday, April 2, 2016 6:14 PM
To: Pedro Mardones <mardones.p at gmail.com>
Cc: r-help mailing list <r-help at r-project.org>
Subject: Re: [R] apply mean function to a subset of data

Hi Pedro,
This may not be much of an improvement, but it was a challenge.

selvec<-as.vector(matrix(c(nsel,unlist(by(toy$diam,toy$group,length))-nsel),
 ncol=2,byrow=TRUE))
TFvec<-rep(c(TRUE,FALSE),length.out=length(selvec))
toynsel<-rep(TFvec,selvec)
by(toy[toynsel,]$diam,toy[toynsel,]$group,mean)

Jim
On 4/3/16, Pedro Mardones <mardones.p at gmail.com> wrote:
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
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.