Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert month year to a date in r [duplicate]

Tags:

date

datetime

r

I need to convert following types of strings to a date format.

Convert "Feb 2009" to 2009-02-01
Convert "Jan 2010" to 2010-01-01
Convert "Mar 2011" to 2011-03-01

I can achieve this from the following code using zoo package.

as.Date(as.yearmon("Feb 2009"))

But due to some constraints I do not want to use this way of converting. So I want to know if there is any other way in R of achieving this task?

like image 451
user3664020 Avatar asked Nov 02 '14 08:11

user3664020


1 Answers

You can paste 01 to the vector using paste and then convert to date by specifying the appropriate format

as.Date(paste('01', v1), format='%d %b %Y')
#[1] "2009-02-01" "2010-01-01", "2011-03-01"

data

v1 <- c("Feb 2009", "Jan 2010", "Mar 2011")
like image 51
akrun Avatar answered Oct 08 '22 19:10

akrun