Renaming Columns in R According to Repeating Sequence

Viewed 434

I have a wide data frame in R and I am trying to rename the column names so that I can reshape it to a long format.

Currently, the data is structured like this:

long lat V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 ... V477

I'd like to rename the columns so that they are:

long lat Jan_1979 Feb_1979 Mar_1979 Apr_1979 ... Sept_2018

I'm not sure how to go about doing this. Any help would be appreciated.

2 Answers

There are multiple ways you could do this.

One way in base R is by using seq to create monthly dates in the format you need. So for example, you could create first 10 sequence starting from 1979-01-01 by

format(seq(as.Date('1979-01-01'), length.out = 10, by = "1 month"), "%b_%Y")

#[1] "Jan_1979" "Feb_1979" "Mar_1979" "Apr_1979" "May_1979" "Jun_1979" "Jul_1979"
#[8] "Aug_1979" "Sep_1979" "Oct_1979"

For your case, this should work

names(df)[3:479] <- format(seq(as.Date('1979-01-01'), 
                           length.out = 477, by = "1 month"), "%b_%Y")

We can use expand.grid to get all month year combinations:

name_combn <- expand.grid(month.abb, 1979:2018)[1:477,]
names(df) <- c('long', 'lat', paste(name_combn$Var1, name_combn$Var2, sep = "_"))

Output:

> head(name_combn, 20)
   Var1 Var2
1   Jan 1979
2   Feb 1979
3   Mar 1979
4   Apr 1979
5   May 1979
6   Jun 1979
7   Jul 1979
8   Aug 1979
9   Sep 1979
10  Oct 1979
11  Nov 1979
12  Dec 1979
13  Jan 1980
14  Feb 1980
15  Mar 1980
16  Apr 1980
17  May 1980
18  Jun 1980
19  Jul 1980
20  Aug 1980
Related