Eraldo Eraldo - 3 months ago 11
R Question

R Problems to transform a number as date

I'm trying to convert a column of a data frame (DA$Date), but I'm not getting it.

In my column has numbers like 1012010 corresponding to 1 January 2010.
I'm using the command


dates <- as.Date (DA $ Date, format = "% d% m% y")


but the result leaves


dates[1]

[1] "10/12/2001"


That does not match the correct date.

Already used the command


dates2 <- as.POSIXct (as.numeric (as.character (DA $ data)), origin = "2010-01-01")


but not got success.

Exemple of column Date


1012010
1012010
1012010
1012010
1012010
1012010
1012010
1012010
1012010
1012010
2012010
2012010
2012010
2012010
2012010
2012010
2012010
2012010
2012010
2012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
3012010
2012010
3012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
4012010
5012010
5012010
5012010
5012010
5012010
5012010
5012010
5012010
5012010
5012010
5012010
3012010
6012010
6012010
2012010
6012010
2012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
6012010
7012010
7012010
7012010
7012010
7012010
7012010
7012010

Answer

We can do this by padding 0 at the front and then use as.Date with format = "%d%m%Y"

as.Date(sprintf("%08d", v1), "%d%m%Y")
#[1] "2010-01-01" "2010-01-06" "2010-01-16" "2010-12-01" "2010-12-15"

data

v1 <- c(1012010, 6012010, 16012010, 1122010, 15122010)