[R] apply mean function to a subset of data
drjimlemon at gmail.com
Sun Apr 3 01:13:57 CEST 2016
This may not be much of an improvement, but it was a challenge.
On 4/3/16, Pedro Mardones <mardones.p at gmail.com> wrote:
> Dear all;
> This must have a rather simple answer but haven't been able to figure it
> out: I have a data frame with say 2 groups (group 1 & 2). I want to select
> from group 1 say "n" rows and calculate the mean; then select "m" rows from
> group 2 and calculate the mean as well. So far I've been using a for loop
> for doing it but when it comes to a large data set is rather inefficient.
> Any hint to vectorize this would be appreciated.
> toy = data.frame(group = c(rep(1,10),rep(2,8)), diam =
> nsel = c(6,4)
> smean <- c(0,0)
> for (i in 1:2) smean[i] <- mean(toy$diam[1:nsel[i]])
> [[alternative HTML version deleted]]
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> PLEASE do read the posting guide
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help