Search code examples
rloopstibblestoring-data

Is there a way in R to store each iteration of a loop into a separate variable?


I am trying to store some descriptive tibbles into separate variables. More specifically, I am summarizing data into tibbles that delineate a list of countries and the population for each country for a certain year (1987-2016). Each iteration represents a year. My current repeat loop (see below) works great, but I'd like to be able to store each iteration into a separate variable so I can later combine those variables into a descriptive visual.

x = 1987
repeat {
  print(subset(data, year == x) %>%
    group_by(country) %>%
    summarize(sum(population)))
    x = x + 1
    if (x > 2016) {
    break
    }
  }

Thanks so much!


Solution

  • You could store the results in a list :

    x = 1987
    l <-list()
    repeat {
      l[[as.character(x)]]<-print(subset(data, year == x) %>%
        group_by(country) %>%
        summarize(sum(population)))
        x = x + 1
        if (x > 2016) {
        break
        }
      }
    l