0

Dataframe:

Number Time 
1       10:25:00
2       10:35:15
3       10:42:26

For each number in the data frame I want to subtract Time, for example:

Number 1 = 10:25:00 - 10:35:15
Number 2 = 10:35:15 - 10:42:26

My code:

for (i in df$Number) {
    for (j in df$Time) {
        subtime <- df$Time[j] - df$Time[j+1]
      }
}

This code only results in NA

2 Answers2

0

Because subtime is reassigned in every loop, only the last value is returned when the loops finish. Further, at the last iteration, j == length(df$Time) so j + 1 is out of bounds, so df$Time[j + 1] will be NA, which means the entire result is NA.

Instead in general you can do:

df$subtime <- c(NA, diff(df$Time))

where NA is the first instance replaced by a suitable default for the first instance. Your case may require additional treatment depending on the exact class of df$Time.

(You should consider creating an MWE of your data if you need further help. What you provided is pretty close, but not quite enough for us to be of help.)

Hugh
  • 15,521
  • 12
  • 57
  • 100
0

I think you may be looking for something like this. The result is given in hours.

For example: 10:25:00 - 10:35:15 = - 00:10:15 = - (10/60) - (15/3600) = -0.1708333

a = data.frame(Number = c(1, 2, 3), Time = c("10:25:00", "10:35:15", "10:42:26"), stringsAsFactors = FALSE)

x = 2

timeDiff = function(x, a){

  as.difftime(a[x, 2]) - as.difftime(a[x+1, 2]) 

}    

result = sapply(2:nrow(a), timeDiff, a)

result

Please note that it's impossible to compute such difference for case Number 3, ever since a fourth row would be necessary, and the data frame you provided has only 3 rows.

As per Stack Overflow's prompt, I can see you r a new user, Thus, for future nested for-loops, I recommend you explore sapply or lapply, as it will make your code look cleaner and easier to maintain.

If you need any further clarification, don't hesitate to comment my answer. :-)