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,
casa=c("Juve","Juve","Hoff","Arsenal",
"Juve","BC","Ajax","BC",
"BC","Hoff","Chelsea","Juve","Juve"),
golfatti=c(1,1,3,4,5,2,3,4,2,1,0,1,2),
away=c("Inter","Inter","Inter","Milan","Milan",
"Inter","Genoa","Milan","Inter", "Spezia","Samp",
"Newcastle","Milan"))
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 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, which is milan and do basically the same.
What can I do? If you need more infos about what i need, don't mind and ask. I really need help. Basically my problem is about the match of df2$away in the df and then tell the loop to select from ID to the two IDs before when the team appear.