Suppose I have a dataframe df with three variables df$x, df$y, df$z, and there is a grouping variable df$g.
Usually, to compute a function WITHIN each group, I do the following
df$new<-unlist(tapply(df$x,df$g,FUN=myfunc))
Now suppose I want to generate residuals from regression of x on y and z WITHIN each value of group g, how do I implement it?
More specifically, without using groups, I would have done
df$new<-resid(lm(df$x ~ df$y + df$z, na.action, na.exclude))
One solution to carry out the previous operation WITHIN groups is to use a loop over unique elements of `df$g', but it would be great if there is any vectorized solution.
ddplyfrom plyr package??by