user3664020
user3664020

Reputation: 3020

Convert numeric values to dates

I have a numeric vector as follows

aa <- c(1022011, 2022011, 13022011, 23022011) (this vector is just a sample, it is very long)

Values are written in such a way that first value is day then month and then year.

What I am doing right now is

as.Date(as.character(aa), %d%m%Y")

but,

it is causing problems (returning NA) in case of single digits day numbers. (i.e. 1022011, 2022011).

so basically

as.Date("1022011", "%d%m%Y") does not work

but

as.Date("01022011", "%d%m%Y")  (pasting '0' ahead of the number) works. 

I want to avoid pasting '0' in such cases. Is there any other (direct) alternative to convert numeric values to dates at once?

Upvotes: 1

Views: 209

Answers (4)

jazzurro
jazzurro

Reputation: 23574

Depending on your platform, you could use sprintf in order to add a zero at the beginning. It seems that Mac is OK with this, but not windows 7 given the discussion with the OP.

aa <- c(1022011, 2022011, 13022011, 23022011)

as.Date(sprintf("%08s", aa), format = "%d%m%Y")

[1] "2011-02-01" "2011-02-02" "2011-02-13" "2011-02-23"

UPDATE

@CathyG kindly mentioned that sprintf("%08i",aa) works on Windows 7.

Upvotes: 3

G. Grothendieck
G. Grothendieck

Reputation: 269586

It could be rearranged using sub in which case a plain as.Date with no format works:

x <- c(1022011, 11022011) # test data

pat <- "^(..?)(..)(....)$"
as.Date(sub(pat, "\\3-\\2-\\1", x))

giving:

[1] "2011-02-01" "2011-02-11"

Upvotes: 5

nrussell
nrussell

Reputation: 18602

You can use dmy in lubridate:

library(lubridate)
aa <- c(1022011, 2022011, 13022011, 23022011)
> dmy(aa)
[1] "2011-02-01 UTC" "2011-02-02 UTC" "2011-02-13 UTC" "2011-02-23 UTC"

and if you don't want the timezone just wrap it in as.Date:

> as.Date(dmy(aa))
[1] "2011-02-01" "2011-02-02" "2011-02-13" "2011-02-23"

Thank you @Ben Bolker,

> as.Date(mdy(aa))
[1] "2011-01-02" "2011-02-02" "2012-01-02" "2011-01-02"

Upvotes: 3

Cath
Cath

Reputation: 24074

I know you don't want to add a "0" but still, in base R, this works :

as.Date(sapply(aa,function(x){ifelse(nchar(x)==8,x,paste("0",x,sep=""))}),format = "%d%m%Y")

Upvotes: 1

Related Questions