1

Say I have a vector of countries and a vector of years

countries = c("Afganistan", "Armenia", ... "Zimbabwe")
year = 2004:2019

I want to create a list which repeats all the countries and adds a year for each repeat, like this:

Afghanistan    2004
Armenia        2004
...
Zimbabwe       2004
Afganistan     2005
Armenia        2005
...
Zimbabwe       2019

This kind of does it

x = data.frame(
    countries   = c("a", "b", "c", "d"),
    years = c(1, 2, 3, 4),
    years2 = c(1, 2, 3, 4)
  )

  melt(data = x, id.vars = "countries", measure.vars = c("years", "years2"))

But there must be an easier way so I don't have to repeat the years variable.

Robin Lindström
  • 622
  • 4
  • 15

1 Answers1

2

Is this what you want?

expand.grid(countries = c("a", "b", "c", "d"),
            years = c(1, 2, 3, 4))
#>    countries years
#> 1          a     1
#> 2          b     1
#> 3          c     1
#> 4          d     1
#> 5          a     2
#> 6          b     2
#> 7          c     2
#> 8          d     2
#> 9          a     3
#> 10         b     3
#> 11         c     3
#> 12         d     3
#> 13         a     4
#> 14         b     4
#> 15         c     4
#> 16         d     4

Created on 2019-12-16 by the reprex package (v0.2.1)

MSR
  • 2,731
  • 1
  • 14
  • 24