Search code examples
rzooas.dateas.yearqtr

Convert first date of the month to yearmon in R


I have been trying to get the year month as a new column to my following example data set.

       time site
1  1/01/2000    A
2  1/02/2000    A
3  1/03/2000    A
4  1/04/2000    A
5  1/05/2000    A
6  1/06/2000    A
7  1/07/2000    A
8  1/08/2000    A
9  1/09/2000    A
10 1/10/2000    A
11 1/11/2000    A
12 1/12/2000    A
13 1/01/2001    A
14 1/02/2001    A
15 1/03/2001    A
16 1/04/2001    A
17 1/05/2001    A
18 1/06/2001    A
19 1/07/2001    A
20 1/08/2001    A
21 1/09/2001    A
22 1/10/2001    A

The data set can be accessed using the following dput.

dta<-structure(list(time = structure(c(1L, 3L, 5L, 7L, 9L, 11L, 13L, 
15L, 17L, 19L, 21L, 22L, 2L, 4L, 6L, 8L, 10L, 12L, 14L, 16L, 
18L, 20L), .Label = c("1/01/2000", "1/01/2001", "1/02/2000", 
"1/02/2001", "1/03/2000", "1/03/2001", "1/04/2000", "1/04/2001", 
"1/05/2000", "1/05/2001", "1/06/2000", "1/06/2001", "1/07/2000", 
"1/07/2001", "1/08/2000", "1/08/2001", "1/09/2000", "1/09/2001", 
"1/10/2000", "1/10/2001", "1/11/2000", "1/12/2000"), class = "factor"), 
    site = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor")), .Names = c("time", 
"site"), class = "data.frame", row.names = c(NA, -22L))

I tried with the following codes and returns the same month for all 12.

library(zoo)
dta$y_m = as.yearmon(as.Date(dta$time,"%m/%d/%Y"))

1] "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000"
 [8] "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2000" "Jan 2001" "Jan 2001"
[15] "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001" "Jan 2001"
[22] "Jan 2001"

Can anybody help me please to get it right. Thank you


Solution

  • Try this:

    require(zoo)
    as.yearmon(dta$time, format="%d/%m/%Y")
    

    Output:

     [1] "Jan 2000" "Feb 2000" "Mar 2000" "Apr 2000" "May 2000" "Jun 2000"
     [7] "Jul 2000" "Aug 2000" "Sep 2000" "Oct 2000" "Nov 2000" "Dec 2000"
    [13] "Jan 2001" "Feb 2001" "Mar 2001" "Apr 2001" "May 2001" "Jun 2001"
    [19] "Jul 2001" "Aug 2001" "Sep 2001" "Oct 2001"