How to create a for loop that allows me to check the same values between two datasets in an interval of datas

Good Evening.
I have two DFs. The first one contains ALL the match played with a unique ID associated. The second one contains only the match played by "BC" when is at home, the goals scored by the away team and the name of the away team.

df <- data.frame(ID=10:22,
                          "Inter","Genoa","Milan","Inter", "Spezia","Samp",
##Second DF
df2 <- df[df$casa=="BC", c("ID","golfatti","away")]```

What I would like to create is a for loop that takes the name of the away team of the second df
(so all the teams against BC) and his ID match(i.e. "Inter" and 15 as ID), 
so for every "i" in df2$away, find the same row in the first DF and calculate the sum of the "golfatti" 
in the two rows before when appear "Inter".

So in this case for i=Inter and ID=15, my loop has to go in df, find the row with df$away=df2$away=="Inter" 
and df$ID==df2$ID=="15" and search the two times before Inter appears and sum the goal scored. 
So it will go behind in the df and the first time Inter appears beofre ID=15, is in ID=12 and sum to
 an empty vector the three goal scored. 
Then, it search again Inter a find that played in ID=11 and sum the goal scored in the vector created before. 
Now the loop has to stop and has to go to the second "i" in df2$away, 
so Milan and it will basically do the same, so go in the first df,
 search the match and calcualte the sum of the two matches before where Milan played.

Let me know if you need more infos. Thank!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.