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.
            Asked
            
        
        
            Active
            
        
            Viewed 34 times
        
    1 Answers
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
- 
                    @孔紫涵 You're welcome. *If* it answers your question, consider selecting it as such (the tick-mark below the up and down-vote arrows). – Anders Ellern Bilgrau Nov 10 '18 at 10:12
