teogj
teogj

Reputation: 343

R: Is it possible to create multiple tables based on unique values by looping?

Say if we have a dataframe such the one below:

region          country   city    
North America   USA       Washington   
North America   USA       Boston
Western Europe  UK        Sheffield
Western Europe  Germany   Düsseldorf
Eastern Europe  Ukraine   Kiev
North America   Canada    Vancouver
Western Europe  France    Reims
Western Europe  Belgium   Antwerp
North America   USA       Chicago
Eastern Europe  Belarus   Minsk
Eastern Europe  Russia    Omsk
Eastern Europe  Russia    Moscow
Western Europe  UK        Southampton
Western Europe  Germany   Hamburg
North America   Canada    Ottawa

I would like to know how to loop through this dataframe in order to check if countries are assigned to the right region, same with cities. Usually I do it helping myself with table() function: however this is very time-consuming as this requires several ad-hoc statements such table(df$country[df$region == 'North America') and so on with all the regions involved and countries as well.

Thus, I'm eager to know how to create a loop so I could be able to get this output economizing as much as possible time and lines of code.

Thanks in advance!

Upvotes: 0

Views: 357

Answers (1)

TobKel
TobKel

Reputation: 1453

df %>% 
  group_by(region) %>% 
  group_split()

Upvotes: 2

Related Questions