Something like this should do the job (in base R):
transform(mtcars, dif_mpg=mpg-ave(mpg, cyl, FUN=mean))
ave
computes FUN
on subgroups of mpg
defined by cyl
. transform
allows you to add/modify columns to a data frame, and also evaluates expressions in the context of the data frame (so you don't have to type out mtcars$mpg
, etc.). Here are the first 6 rows of the result:
mpg cyl disp hp drat wt qsec vs am gear carb dif_mpg
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 1.25714286
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 1.25714286
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 -3.86363636
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 1.65714286
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 3.60000000
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 -1.64285714
Other alternatives include dplyr
package (as shown by David Robinson), data.table
:
library(data.table)
(data.table(mtcars, keep.rownames=T)[, dif_mpg:=mpg - mean(mpg), by=cyl])
And plyr
(though you should use dplyr
over plyr
, as it is much faster):
library(plyr)
ddply(mtcars, "cyl", transform, dif_mpg=mpg-mean(mpg))