Add a second to duplicate POSIXct dates

I am trying to add single seconds to repeating dates in my data frame.

i.e. from this:

       value                date
       18        2013-07-09 16:49:23
       62        2013-07-09 18:01:36
       64        2013-07-09 18:46:51
       29        2013-07-09 18:46:51
       22        2013-07-09 18:46:51
....

I would like to get the following:

       value                date
       18        2013-07-09 16:49:23
       62        2013-07-09 18:01:36
       64        2013-07-09 18:46:51
       29        2013-07-09 18:46:52
       22        2013-07-09 18:46:53
....

I understand that I can simply add + 1 or +2 to the POSIXct format to add seconds, however I do not know how to select duplicates. Please note that my framework is several hundred lines long, and the date can be displayed up to 20 times in a row.

I am thinking of doing something in this direction:

for (item in duplicated(dataframe$date)) {
    if (item == TRUE) {
        for (n in 1:#length of duplicated dates) {
        dataframe[index(item) +n]$date <- (dataframe[index(item) +n]$date +n)
        } } }

Thank you for your help!

+4
source share
2 answers

You can use make.index.uniquethe xts package.

x <- structure(list(value = c(18, 62, 64, 29, 22),
  date = structure(c(1373406563, 1373410896, 1373413611, 1373413611, 1373413611),
  class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("value", "date"),
  row.names = c(NA, -5L), class = "data.frame")
x$date.unique <- make.index.unique(x$date,1)
x
#   value                date         date.unique
# 1    18 2013-07-09 16:49:23 2013-07-09 16:49:23
# 2    62 2013-07-09 18:01:36 2013-07-09 18:01:36
# 3    64 2013-07-09 18:46:51 2013-07-09 18:46:51
# 4    29 2013-07-09 18:46:51 2013-07-09 18:46:52
# 5    22 2013-07-09 18:46:51 2013-07-09 18:46:53
+5
source

rle . sequence, , .

r <- rle(as.numeric(df$date))$lengths
r
# [1] 1 1 3

to.add <- sequence(r) - 1
to.add
# [1] 0 0 0 1 2

df$date2 <- df$date + to.add

# Suggestion from @agstudy to make it more general:
df$date2 <- df$date + as.difftime(to.add, unit = "secs")

df[ , c("date", "date2")]
#                  date               date2
# 1 2013-07-09 16:49:23 2013-07-09 16:49:23
# 2 2013-07-09 18:01:36 2013-07-09 18:01:36
# 3 2013-07-09 18:46:51 2013-07-09 18:46:51
# 4 2013-07-09 18:46:51 2013-07-09 18:46:52
# 5 2013-07-09 18:46:51 2013-07-09 18:46:53

?zoo ( ).

+6

All Articles