0

I have a data frame in which one of my variable is a character. I want to convert it into a date value. It looks like

var
[1] "Apr 2010" "Apr 2011" "Apr 2012" "Apr 2013"

class of my variable is a character.

I tried the below command but it is giving me NA

as.Date("Apr 2010", format = "%b %Y")
 [1] NA

Is there any way to solve this kind of problem. Note:- I don't want to add any day . I just want to keep it clean as Month-Year format. There are question regarding conversion of date from character to data on stackoverflow but I do not find similarity with my problem. If you know any resource then please provide it.

learner
  • 828
  • 2
  • 19
  • 36
  • `Apr 2010` is not a valid `Date` because there is no day component. Just add an arbitrary day value, e.g. `as.Date(sprintf("%s 01", "Apr 2010"), format = "%b %Y %d")`. – nrussell May 31 '16 at 18:07
  • Also look at the `yearmon` class in package:zoo. Also .... please search for answers before posting. (My search strategy was "[r] year month date" – IRTFM May 31 '16 at 18:08
  • I gone through all the solution but none is able to solve the way I want. I am looking to convert 'Apr 2010' to Apr 2010 (month-year) format without adding any day. Is it possible in R. Please help – learner Jun 01 '16 at 04:14
  • library(zoo) x <- c("Apr 2010", "Apr 2011" ,"Apr 2012" ,"Apr 2013") x <- as.Date(as.yearmon(x)) print(x) [1] "2010-04-01" "2011-04-01" "2012-04-01" "2013-04-01" – Arun kumar mahesh Jun 01 '16 at 05:08
  • @Arunkumarmahesh I already mentioned that I don't want day in my output. Please provide solution – learner Jun 01 '16 at 06:00
  • @user110244 use gsub function :gsub(".{3}$","",x) print(x) [1] "2010-04" "2011-04" "2012-04" "2013-04" – Arun kumar mahesh Jun 01 '16 at 06:27

0 Answers0