0

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!

Phil
  • 7,287
  • 3
  • 36
  • 66
maudib528
  • 51
  • 1
  • 7
  • 2
    Why not group by `year` and `country`? – jogo Jul 10 '20 at 18:02
  • `aggregate(population ~ year + country, data=data, FUN=sum)` https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family – jogo Jul 10 '20 at 18:56

2 Answers2

1

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
Waldi
  • 39,242
  • 6
  • 30
  • 78
0

You can do this with assign() like this:

for (i in 1990:2000) {
  assign(paste0('year_', i, "_dat"), i)
}

Not sure if that is the best way to accomplish your larger task, but assign() will do what you want. Seems like i will be a dataframe in your case, which will work fine.

assign() creates a variable in the environment and takes a name and an object as arguments - perfect for your case. We can use paste0() to dynamically generate the variable name with something we are looping over and give it any object to assign to that name.

BHudson
  • 687
  • 4
  • 11
  • Thank you! However, what would you recommend the best way to accomplish my larger task? I'm relatively new to R, so I'd love any thoughts/advice! – maudib528 Jul 10 '20 at 18:39
  • `fortunes::fortune(236)` https://stackoverflow.com/questions/17559390/why-is-using-assign-bad – jogo Jul 10 '20 at 18:53