Here a solution that makes use of num_range
for tidy selection of the columns before the call to pivot_longer
:
library(dplyr)
library(tidyr)
df_long <- df %>%
select(Region, num_range("X", 1975:1999)) %>%
pivot_longer(-Region,
names_to = "Year",
names_prefix = "X",
values_to = "Population")
> df_long
# A tibble: 850 x 3
Region Year Population
1 National Total 1975 92420
2 National Total 1976 93717
3 National Total 1977 94974
4 National Total 1978 96259
5 National Total 1979 97542
6 National Total 1980 98705
7 National Total 1981 100072
8 National Total 1982 101654
9 National Total 1983 103008
10 National Total 1984 104357
# ... with 840 more rows