用于过滤足球比赛的循环

时间:2016-04-02 12:23:32

标签: r loops

我正在尝试编写一个循环,用于过滤由特定团队与AwayTeam一起玩的HomeTeam。所以最后我可以有一个专栏,告诉我一个特定球队在过去对阵AwayTeam时赢得/输掉比赛的数量。所以原始数据集如下所示:

         Date   HomeTeam   AwayTeam  FTHG  FTAG   FTR  Draw  Lost   Win 
        (chr)      (chr)      (chr) (int) (int) (chr) (dbl) (dbl) (dbl)  
1 17/08/2002  Blackburn Sunderland     0     0     D     1     0     0      
2 17/08/2002   Charlton    Chelsea     2     3     A     0     1     0      
3 17/08/2002    Everton  Tottenham     2     2     D     1     0     0      
4 17/08/2002     Fulham     Bolton     4     1     H     0     0     1      
5 17/08/2002      Leeds   Man City     3     0     H     0     0     1      
6 17/08/2002 Man United  West Brom     1     0     H     0     0     1      

我先写了这段代码:

arsenal <- football %>% 
  select(1:10) %>% 
  filter(football$HomeTeam == "Arsenal" & football$AwayTeam == "Birmingham" & Date >= 17/08/2002)
birmingham <- football %>% 
  select(Date, HomeTeam, AwayTeam, FTHG, FTAG, FTR) %>% 
  filter(football$HomeTeam == "Birmingham" & football$AwayTeam == "Arsenal" & Date >= 17/08/2002)

它产生了以下内容:

        Date HomeTeam   AwayTeam  FTHG  FTAG   FTR  Draw  Lost   Win 
       (chr)    (chr)      (chr) (int) (int) (chr) (dbl) (dbl) (dbl) 
1 18/08/2002  Arsenal Birmingham     2     0     H     0     0     1      
2   01/05/04  Arsenal Birmingham     0     0     D     1     0     0      
3   04/12/04  Arsenal Birmingham     3     0     H     0     0     1      
4   02/10/05  Arsenal Birmingham     1     0     H     0     0     1     
5   12/01/08  Arsenal Birmingham     1     1     D     1     0     0      
6   17/10/09  Arsenal Birmingham     3     1     H     0     0     1  
         Date   HomeTeam AwayTeam  FTHG  FTAG   FTR
       (chr)      (chr)    (chr) (int) (int) (chr)
1 12/01/2003 Birmingham  Arsenal     0     4     A
2   22/11/03 Birmingham  Arsenal     0     3     A
3   15/05/05 Birmingham  Arsenal     2     1     H
4   04/02/06 Birmingham  Arsenal     0     2     A
5   23/02/08 Birmingham  Arsenal     2     2     D
6   27/03/10 Birmingham  Arsenal     1     1     D

所以我想为所有团队自动化这个过程,就像上面的例子一样。我已经产生了以下循环,但它不起作用:

list_of_teams <- c("Arsenal", "Aston Villa", "Manchester City", "Liverpool")
for(i in 1:length(list_of_teams)){ football_1 <- football %>% 
    select(1:10) %>% 
    filter(football$HomeTeam == list_of_teams[i] & football$AwayTeam == list_of_teams[i+1])
for(j in 1:length(list_of_teams[-i])){
    football$HomeTeam == list_of_teams[j] & football$AwayTeam == list_of_teams[-i]
    print(c(list_of_teams[[i]], list_of_teams[-i][[j]]))
  }
}

计划是创建空数据框,然后根据产生的循环将其存储在那里。但是,最终它只会存储最初创建的list_of_teams变量中的团队。 问题是:为什么循环忽略/或没有选择列1:10并相应地过滤HomeTeam和AwayTeam以及我们如何解决这个问题? 提前感谢您,我是R的新手并且编程任何帮助将不胜感激。

0 个答案:

没有答案