George.QGIS
George.QGIS

Reputation: 11

Trouble with as.Date

I currently have date data in the following format: DDMMYYYY

I want to convert the dates to proper date function (I suspect I will need to for visualizing the temporal data) using the following:

data$DATE<-as.Date(as.character(data$DATE), "%d%m%Y")

which would be fine, however days with single digits cause me to get NA results because there is no 0 infront.

Example:

17042018  = 2018-05-10
 5022018  = NA

What is a work around? Should I just paste a 0 in instances where characters is less than 8?

I am quite new to R, but if you could send me in the right direction it would be much appreciated!

Regards, G

Upvotes: 1

Views: 551

Answers (1)

GGamba
GGamba

Reputation: 13680

Pad the string with zeros till length 8, then convert:

a <- '5102017'
a <- sprintf('%08d', as.numeric(a))
as.Date(a, "%d%m%Y")

Or, in your example:

data$DATE <- as.Date(sprintf('%08d', as.numeric(data$DATE)), "%d%m%Y")

You may have to transform the initial data$DATE, depending on what you are strarting from

Upvotes: 1

Related Questions