s_boardman
s_boardman

Reputation: 416

Calculating relative time series in R

I have a dataframe (example below) which I want to pass to a function which will take absolute time values (which are in POSIXct format) and turn them into a relative time series.

ID          Observation
M97         11/09/2013 10:35
M97         11/09/2013 13:13

I'm not that experienced with R functions so am struggling to get my head round writing it. I've got some pseudocode to start (shown below) to give the concept of what I want to do.

relative_time <- function(df) {
    #for each row in the dataframe:
        #subtract the Observation value from the Observation value of the first row
        #Append the returned value to the end of the row in a new column called RelativeTime
}

The output I want to achieve is as follows:

ID          Observation         RelativeTime
M97         11/09/2013 10:35    0
M97         11/09/2013 13:13    148

I've looked at this question amongst other things. But am stuck because the R syntax of a "for loop" is throwing me.

Any help is much appreciated!

Upvotes: 0

Views: 1491

Answers (1)

Spacedman
Spacedman

Reputation: 94237

Use diff but pad with a zero because there's one fewer diffs than there are data points. Let's make a data frame using R's POSIXct date class:

> d=data.frame(Observation=as.POSIXct(c("2014-08-06 14:46:14 BST","2014-08-06 14:36:14 BST","2014-08-06 16:56:14 BST")))
> d
          Observation
1 2014-08-06 14:46:14
2 2014-08-06 14:36:14
3 2014-08-06 16:56:14

No loops required:

> d$RelativeTime = c(0,diff(d$Observation))
> d
          Observation RelativeTime
1 2014-08-06 14:46:14            0
2 2014-08-06 14:36:14          -10
3 2014-08-06 16:56:14          140

Note these diffs are in minutes, if you want seconds:

> d$RelativeTime = c(0,diff(d$Observation)*60)
> d
          Observation RelativeTime
1 2014-08-06 14:46:14            0
2 2014-08-06 14:36:14         -600
3 2014-08-06 16:56:14         8400

Upvotes: 3

Related Questions