1

I have a dataframe where I have three columns that basically are Country, Year, and Value. I am trying to extract a dataframe for each of the unique countries. I am using the dplyr library like:

USA<-filter(df, Country=="USA")

I can filter all of the countries like that, but doing so seems like a very repetitive task, so I am trying to find a way of doing it more efficiently.

I am thinking in a For cycle but I don't really know how to script it. Here is what I tried.

for(i in unique(df$Country)){
  i<-filter(df, Country==i)
}

It actually generates a df but it only includes the observations for the last element in the unique(df$Country) part.

Thank you very much.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

0

This is not a very elegant answer, but you could use split to put each group (i.e., country) into a list of dataframes. Then, you can add them to your global environment.

# This will give you list of dataframes by country.
list_data <- split(df, df$Country)

# Assign names to each dataframe based on country.
names(list_data) <- paste0("df_", names(list_data))

# Then, add each dataframe to your local environment.
list2env(list_data, .GlobalEnv)

Or if you want to stick with a for loop, then you can do this:

for(i in unique(as.character(df$Country))) {
    nam <- paste("df", i, sep = ".")
    assign(nam, df[df$Country==i,])
}
AndrewGB
  • 16,126
  • 5
  • 18
  • 49