[R] apply mean function to a subset of data
mardones.p at gmail.com
Sat Apr 2 20:46:52 CEST 2016
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]]
More information about the R-help