for (l in 1:G) // for each group group_mu[g] <- mean(mu[group==g])); That assumes the values are ordered by group. If they're not then you can pass in an array of integer arrays containing the indices corresponding to each group and then use mu[idx[g]], where idx[g] is the array of indices for group g.
Hope that helps,
Jonah