0

I want to create about 20 new dataframes, and I want the names of these dataframes to be 'matches_[country]' where [country] is the name of a country in countries_list. I thought a for loop would be the solution but I can't get it to work.

This is what I tried (results is the df):

countries_list = list('Netherlands', 'England', 'Brazil', 'Argentina', 'Germany', 'France', 'Spain', 'Italy', 'Portugal', 'Croatia', 'Uruguay', 'Mexico')

for (i in countries_list) {
  matches_i = filter(results, home_team == 'i' | away_team == 'i')
}

With this, I thought I would get a dataframe for each of the countries in the list, with in each dataframe all the matches that that country played, either as the home or away team. However, it creates matches_i without any data.

Edit: Results is a table with international soccer matches, each match is a row and columns are date, home_team, away_team, home_score, away_score, tournament etc.

How could I solve this?

Phil
  • 7,287
  • 3
  • 36
  • 66
maxi888
  • 1
  • 1
  • Please `dput(results)` and paste the result in the question! – Duck Aug 27 '20 at 16:24
  • 1
    first dont do `'i'` – Onyambu Aug 27 '20 at 16:48
  • Results is a table with international soccer matches, each match is a row and columns are date, home_team, away_team, home_score, away_score, tournament etc. – maxi888 Aug 27 '20 at 17:30
  • Are you looking for [Dynamically select data frame columns using $ and a vector of column names](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-vector-of-column-names)? – Rui Barradas Aug 27 '20 at 18:01

1 Answers1

0

You had some good ideas. But adding an i on an objectname won't match 'matches_[country]'. You will just end up having an object named matches_i. And home_team == 'i' will look for an country named i not the actual country name (That's the reason your dataframe is empty. There is no country named i). home_team == i (without quotation marks) will do the trick.

So I made up a smaller results dataset and a shorter countries list as an example.

results <- data.frame(home_team = c('Netherlands', 'England', 'Brazil'),
                      away_team = c("Spain", "Italy", "England"))

countries <- list('Netherlands', 'England', "Brazil", "Spain", "Italy") 

And here is the loop that generates an dataset for each country in the list.

                       
for (i in countries) {
  matches <- filter(results, home_team == i | away_team == i)
  assign(paste("matches_", i, sep = ""), matches)
}
tamtam
  • 3,541
  • 1
  • 7
  • 21