Reputation: 101
I want to convert df to xts with year end-of-month date index (i.e., 1989-12-31). I searched web but without answers. Thanks and appreciate your help.
df <- read.table(textConnection("
date a b c d
198912 29.46 13.47 32.52 22.06
199001 36.35 17.30 38.14 24.98
199002 33.72 15.57 38.14 23.61
199003 30.76 14.01 34.74 21.73
"),header=T)
Upvotes: 3
Views: 1772
Reputation: 115392
Use the yearmon
class and then as.Date.yearmon
to quote from help('yearmon')
:
as.Date.yearmon and as.yearmon.yearqtr each has an optional second argument of "frac" which is a number between 0 and 1 inclusive that indicates the fraction of the way through the period that the result represents. The default is 0 which means the beginning of the period.
as.Date(as.yearmon(as.character(df$date), format = '%Y%m'), frac=1)
## [1] "1989-12-31" "1990-01-31" "1990-02-28" "1990-03-31"
Upvotes: 4
Reputation: 93813
And for laughs, here is a base R method, which is admittedly quite ugly:
Reduce(c,
lapply(
as.Date(paste0("1-",as.character(df$date)),format="%d-%Y%m"),
function(x) seq.Date(x,length=2,by="1 month")[2] - 1
)
)
[1] "1989-12-31" "1990-01-31" "1990-02-28" "1990-03-31"
Upvotes: 3