0

enter image description here

var1 is a numeric variable i try as.Date many times but it did not work I want to change the 201401(year-month) to date variable.

  • 1
    Assuming your data.frame is named `df`, then do `as.Date(paste0(df$Var1, "01"), format="%Y%m%d")` – DanY Nov 06 '18 at 21:34

1 Answers1

0

Dates also need a day, and you do not have that. So you need to assume which day of the month your are looking at:

dat <- data.frame(var1 = c(201401, 201402, 201403), Freq=sample(1:3))

assumed_day <- 15

dat$date <- as.Date(paste(dat$var1, assumed_day), format = "%Y%m %d")

print(dat)        
#    var1 Freq       date
#1 201401    1 2014-01-15
#2 201402    2 2014-02-15
#3 201403    3 2014-03-15

See as.Date.

Using the format and other related function you can format the dates however you like:

dat$formatted <- paste(months(dat$date), format(dat$date, "%Y"))

print(dat)
#    var1 Freq       date     formatted
#1 201401    1 2014-01-15  January 2014
#2 201402    3 2014-02-15 February 2014
#3 201403    2 2014-03-15    March 2014
Anders Ellern Bilgrau
  • 9,928
  • 1
  • 30
  • 37