I have a dataset with individual decisions taken in groups. For each individual I need an aggregated (let's say, sum) of all decisions of his/her group members. So let's say the data looks like:
set.seed(123)
group_id <- c(sapply(seq(1, 3), rep, times = 3))
person_id <- rep(seq(1,3),3)
decision <- sample(1:10, 9, replace=T)
df <-data.frame(group_id, person_id, decision)
df
The result is:
group_id person_id decision
1 1 1 3
2 1 2 8
3 1 3 5
4 2 1 9
5 2 2 10
6 2 3 1
7 3 1 6
8 3 2 9
9 3 3 6
And I need to produce something like that:
group_id person_id decision others_decision
1 1 1 3 13
2 1 2 8 8
3 1 3 5 11
So for each element of the group, I get all other members of the same group and do something (a sum). I can do this with just a for loop but it seems ugly and inefficient. Are there better solutions?
UPDATE:
Here is the solution I figured out so far, sorry for ugliness:
df$other_decision=unlist(by(df, 1:nrow(df), function(row) {
df %>% filter(group_id==row$group_id, person_id!=row$person_id) %>% summarize(sum(decision))
}
))
df