Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine separate Year and Month columns into single Date Column

Tags:

r

I have a data frame (df) like this:

    code     year  month
1 YYOOGG    2011    8
2 YYOOGG    2011    1
3 YYOOGG    2011    4
4 YYOOGG    2011    3
5 YYOOGG    2011    12
6 YYOOGG    2011    9

and I need to create a 4th column with the Date like this:

    code     year  month  Date
1 YYOOGG    2011    8     2011-08
2 YYOOGG    2014    1     2014-01
3 YYOOGG    2016    4     2016-04
4 YYOOGG    2009    3     2009-03
5 YYOOGG    2000    12    2000-12
6 YYOOGG    2010    9     2010-09

I tried this:

  df$Date <- as.Date(paste(df$year, df$month, sep="-"), "%Y-%M")

but I get the following as the date:

2011-09-09

like image 502
Cybernetic Avatar asked Sep 09 '16 21:09

Cybernetic


People also ask

How do I merge month and year columns in pandas?

Combining Month, Year and Day columns with Pandas apply()And then use lambda function to combine the three values in a row using join() function.

How do I combine the month and year of a column in Excel?

Concatenate year, month and day to date with formulaSelect a blank cell to place the concatenated date, and enter formula =A2&"/"&B2&"/"&C2 into the formula bar, then press the Enter key. 2. Drag the populated cell's Fill Handle down to the cells for concatenating corresponding cells to date.


1 Answers

I'd use zoo::as.yearmon as follows

df$Date <- as.yearmon(paste(df$year, df$month), "%Y %m")

It will not look like the desired output (i.e. 2011-01).

However, IMO this approach is better than m0h3n's because df$Date will be saved as a yearmon object rather than a string. Therefore you can be handled it like a date. For example, if you save df$Date as a string you're going to have a hard time plotting your data over time, etc...

like image 82
Jacob H Avatar answered Oct 05 '22 03:10

Jacob H