Search code examples
rxtsquantmodstrptime

strptime() behaving differently in an anonymous function than I expected


I have an xts list object, I am trying to get the dates present in my list put then in a vector to be used latter as xts index in further processing. Although my data include a time stamp, for the purpose of this illustration I am pulling YHOO data from google. This data doesn't have the time element of a time stamp only date but it's good enough. You need quantmod. I pull the data, then create a list to divide YHOO into weekly sub-components with the following code:

library(quantmod)
library(xts)

getSymbols("YHOO",src="google")
yhooL <- split.xts(YHOO,"weeks")

To get the date from the first piece of yhooL I pass this code:

strptime(index(yhooL[[1]][1]),format="%Y-%m-%d")

It works as expected and I get my date. But to get all of the dates from the first row of each week using vapply strptime() returns all its eleven elements $sec, $min...days, week of year. It doesn't give me the date in the format I provided. What I am trying to achieve is return the date from the first row in that particular format. I am not sure what value to pass to argument FUN.VALUE of vapply()

vapply(yhooL, function(i) {strptime(index(i[1,]), format ="%Y-%m-%d")},double(1))

I also tried POSIXct(1) for FUN.VALUE and a bunch of other, was guessing without luck really.


Solution

  • This is because strptime returns a POSIXlt object, which is pretty complicated. You are better off using lapply to pick the indices out and then using do.call to combine them after. You can also set the class of the final object in this way, eg using as.Date.

    x <- do.call(c,lapply(yhooL, function(i) as.Date(index(i)[1])))
    summary(x)
            Min.      1st Qu.       Median         Mean      3rd Qu.         Max. 
    "2007-01-03" "2009-04-02" "2011-07-05" "2011-07-04" "2013-10-03" "2016-01-04" 
    class(x)
    [1] "Date"