Merging the aggregate data back into the original data
Often, you will want to augment your original data with some of the calculated data as derived previously. In these cases, you can merge the data back into the original data using a common key. Again, we will use the dplyr
package to take the results just obtained (by.cat
) and join them back to the original data (x
), using the common key cat
.
We will be using a left_join
just for an example; however, we could have used a right join to obtain the same results, since by.cat
was completely derived from x
. After joining the two dataframes, we will end up with a new dataframe named x2
:
# Merge the summary measures back into the original data. Merge by cat. x2 <- by.cat %>% left_join(x, by = "cat") head(x2) > Source: local data frame [6 x 9] > > cat Avg.Total.Insured Avg.People Year Year.1 Total.People > (fctr) (dbl) (dbl) (fctr) (int) (dbl) > 1 ALL AGES ...