简体   繁体   中英

convert year and month into date format

I have dates in format

192607 192608

and want to transform them so that they are in the following format and can be used for a xts object

1926-07-01 1926-08-01

I have tried working with as.date and paste() but couldn't make it work. Help is very much appreciated. Thank you!!

You need to paste then put format date. Something like this:

dates <- c("192607", "192608")
dates  <- paste0(dates,"01")
dates <- as.Date(dates, format ="%Y%m%d")
dates

The result is

[1] "1926-07-01" "1926-08-01"

Assuming all the dates will be converted to the first of the month, this lubridate solution works.

library(lubridate)

dates <- c(192607, 192608)

dates <- paste0(dates, '01') # add 01 for day of month

# output: "19260701" "19260801"

dates <- ymd(dates)

# output: "1926-07-01" "1926-08-01"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM