1

I'm trying to calculate the total number of matches played by each team in the year 2019 and put them in a table along with the corresponding team names

teams<-c("Sunrisers Hyderabad", "Mumbai Indians", "Gujarat Lions", "Rising Pune Supergiants",
         "Royal Challengers Bangalore","Kolkata Knight Riders","Delhi Daredevils",
         "Kings XI Punjab", "Deccan Chargers","Rajasthan Royals", "Chennai Super Kings",
         "Kochi Tuskers Kerala", "Pune Warriors", "Delhi Capitals", " Gujarat Lions")

for (j in teams) {
    print(j)
    ipl_table %>%
    filter(season==2019 & (team1==j | team2 ==j)) %>%
    summarise(match_count=n())->kl
      print(kl)
match_played<-data.frame(Teams=teams,Match_count=kl)
} 

The match played by last team (i.e Gujarat Lions is 0 and its filling 0's for all other teams as well.

The output match_played can be found on the link given below.

enter image description here

I'd be really glad if someone could help me regarding this error as I'm very new to R.

Deepansh Arora
  • 724
  • 1
  • 3
  • 15

2 Answers2

2

filter for the particular season, get data in long format and then count number of matches.

library(dplyr)

matches %>%
  filter(season == 2019) %>% 
  tidyr::pivot_longer(cols = c(team1, team2), values_to = 'team_name') %>%
  count(team_name) -> result

result

#  team_name                       n
#  <chr>                       <int>
#1 Chennai Super Kings            17
#2 Delhi Capitals                 16
#3 Kings XI Punjab                14
#4 Kolkata Knight Riders          14
#5 Mumbai Indians                 16
#6 Rajasthan Royals               14
#7 Royal Challengers Bangalore    14
#8 Sunrisers Hyderabad            15
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Here is an example

library(tidyr)
df_2019 <- matches[matches$season == 2019, ] # get the season you need
df_long <- gather(df_2019, Team_id, Team_Name, team1:team2) # Make it long format
final_count <- data.frame(t(table(df_long$Team_Name)))[-1] # count the number of matches
names(final_count) <- c("Team", "Matches") 
                     Team     Matches
1         Chennai Super Kings      17
2              Delhi Capitals      16
3             Kings XI Punjab      14
4       Kolkata Knight Riders      14
5              Mumbai Indians      16
6            Rajasthan Royals      14
7 Royal Challengers Bangalore      14
8         Sunrisers Hyderabad      15

Or by using base R

final_count <- data.frame(t(table(c(df_2019$team1, df_2019$team2))))[-1]
names(final_count) <- c("Team", "Matches") 
final_count
Agaz Wani
  • 5,514
  • 8
  • 42
  • 62