Haroon Lone
Haroon Lone

Reputation: 2949

set seconds to 0 of xts object

I have a list of xts objects and each object is having varying no. of seconds. How should I set seconds to 0. Here, I am providing one xts object

structure(c(6.00001082143504e-18, 6.00001082143504e-18, 6.00001082143504e-18, 
6.00001082143504e-18, 6.00001082143504e-18, 6.00001082143504e-18
), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", 
"POSIXt"), tzone = "", class = c("xts", "zoo"), index = structure(c(1438367432, 
1438367492, 1438367552, 1438367612, 1438367672, 1438367732), tzone = "", tclass = c("POSIXct", 
"POSIXt")), .Dim = c(6L, 1L))

In other words, I have xts object as

2015-08-01 00:00:32 6.000011e-18
2015-08-01 00:01:32 6.000011e-18
2015-08-01 00:02:32 6.000011e-18

How should I set seconds to 0 so that it will result into

2015-08-01 00:00:00 6.000011e-18
2015-08-01 00:01:00 6.000011e-18
2015-08-01 00:02:00 6.000011e-18

Upvotes: 3

Views: 802

Answers (2)

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

It's usually not a good idea to change timestamps to be earlier than observed, so you should carefully reconsider doing this. If you provide more information on the actual problem you're trying to solve, I can probably help you avoid doing something as potentially dangerous as changing your data to have occurred before it actually did.

align.time will (safely) round the timestamp up to the nearest n seconds:

> align.time(x, n=60)
                            [,1]
2015-07-31 13:31:00 6.000011e-18
2015-07-31 13:32:00 6.000011e-18
2015-07-31 13:33:00 6.000011e-18
2015-07-31 13:34:00 6.000011e-18
2015-07-31 13:35:00 6.000011e-18
2015-07-31 13:36:00 6.000011e-18

Or, if you must, you can just use trunc to remove the seconds all-together:

> index(x) <- as.POSIXct(trunc(index(x), units="mins"))
> x
                            [,1]
2015-07-31 13:30:00 6.000011e-18
2015-07-31 13:31:00 6.000011e-18
2015-07-31 13:32:00 6.000011e-18
2015-07-31 13:33:00 6.000011e-18
2015-07-31 13:34:00 6.000011e-18
2015-07-31 13:35:00 6.000011e-18

Upvotes: 2

akrun
akrun

Reputation: 887911

We may use sub. We match the two digits (\\d{2}) before the end of the string ($) and replace it with 00 of the index of the 'xt2'. As the return object is character class, we can reconvert it to POSIXct class before assigning it back as the index of the original object.

index(xt2) <- as.POSIXct(sub('\\d{2}$', '00', index(xt2)))

Upvotes: 2

Related Questions