you could use gather
and unite
for this:
library(dplyr)
library(tidyr)
# example data
mat <- (matrix(rnorm(12*8, mean = 800, sd = 200), nrow = 12))
df <- data.frame(months = month.abb, mat)
colnames(df)[-1] <- 2008:2015
# months 2008 2009 2010 2011 2012 2013 ...
# 1 Jan 578.1627 1005.3642 622.2480 738.3829 448.1257 1112.2660
# 2 Feb 950.1085 857.4998 866.0585 629.5612 848.3288 714.2643
# 3 Mar 650.0593 852.8997 797.3760 719.5924 696.3195 793.7964
# ...
df %>% gather(year, Value, - months) %>%
unite(Month, year, months, sep = "-")
# Month Value
# 1 2008-Jan 578.1627
# 2 2008-Feb 950.1085
# 3 2008-Mar 650.0593
# 4 2008-Apr 590.9742
# 5 2008-May 671.8589
# 6 2008-Jun 829.1035
# 7 2008-Jul 755.9633
# 8 2008-Aug 824.7879
# ...
If you want the months to be represented as numbers and you know that your data set is of the same order as in your picture, you could mutate
that variable to be represented as number from 1:12
library(stringr)
df %>% mutate(months = str_pad(1:12, 2,pad = "0")) %>%
gather(year, Value, - months) %>%
unite(Month, year, months, sep = "-")
# Month Value
# 1 2008-01 578.1627
# 2 2008-02 950.1085
# 3 2008-03 650.0593
# 4 2008-04 590.9742
# 5 2008-05 671.8589
# 6 2008-06 829.1035
# ...