Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R read dates in format yyyymmdd [duplicate]

Tags:

date

r

I have a dataset, the first column has the date field with yyyymmdd formats. I tried to convert these dates to R format using:

    yield.usd$Fecha <- as.Date(yield.usd$Fecha, format='%Y%m%d')

and the output is:

Error in as.Date.numeric(yield.usd$Fecha, format = "%Y%m%d") : 'origin' must be supplied

Then I tried:

    yield.dates <- as.Date(yield.usd[1], format='%Y%m%d')

the output as follows:

Error in as.Date.default(yield.usd[1], format = "%Y%m%d") : do not know how to convert 'yield.usd[1]' to class “Date”

How can I make R read those dates?

The dput(head(yield.usd)) as follows:

structure(list(Fecha = c(20120815L, 20120815L, 20120815L, 20120815L, 
20120815L, 20120815L), Plazo = 1:6, Soberana = c(0.001529738, 
0.001558628, 0.001587518, 0.001616408, 0.001645299, 0.001674189
), AAA = c(0.009642716, 0.009671607, 0.009700497, 0.009729387, 
0.009758277, 0.009787168), AA. = c(0.017483959, 0.01751285, 0.01754174, 
0.01757063, 0.01759952, 0.017628411), AA = c(0.017762383, 0.017791273, 
0.017820163, 0.017849053, 0.017877944, 0.017906834), AA..1 = c(0.018207843, 
0.018236733, 0.018265624, 0.018294514, 0.018323404, 0.018352294
), A = c(0.036340293, 0.036369183, 0.036398073, 0.036426964, 
0.036455854, 0.036484744)), .Names = c("Fecha", "Plazo", "Soberana", 
"AAA", "AA.", "AA", "AA..1", "A"), row.names = c(NA, 6L), class = "data.frame")   
like image 718
capm Avatar asked Aug 08 '13 01:08

capm


1 Answers

Your dates are in number format, so R thinks it represents a timestamp (in such case it needs origin of timestamp, usually 1st January 1970). What you want is comprehension from strings, so you should convert your numbers to characters first:

as.Date(as.character(yield.usd$Fecha), format='%Y%m%d')
like image 71
sashkello Avatar answered Sep 21 '22 08:09

sashkello