I have a data.frame for aggregation which is simply done by ddply
from plyr. The target now is to write a function that bind the aggregation object automatically to the original data. The problem is, that there can be more then one aggregation variable.
The following refers to an example with only one aggregation variable:
Here the dataframe I have:
M O
1 1 6
2 2 7
3 2 4
4 1 6
Then with ddply
I get the aggregation for "O":
TEST <- ddply(.data = DF,
.variables = c("M"),
.fun = summarise,
NEW = sum(O))
The result looks like:
M NEW
1 1 12
2 2 11
What I wanna do now is to write a function that enables me to bind the variable "New
" to the original data.frame.
In a loop it works with:
for(i in 1:nrow(TEST)) {
DF$New[DF$M == TEST$M[i]] <- TEST$NEW[i]
}
M O New
1 1 6 12
2 2 7 11
3 2 4 11
4 1 6 12
Now I wanna transform this into a function that gives an equivalent output even when there are more then just one aggregation variable.