Home > OS >  In R how do I combine two numeric columns to create minute:second?
In R how do I combine two numeric columns to create minute:second?

Time:03-14

I have a data-frame that contains a minute & second column, both numeric:

enter image description here

I have been able to create a new column by combining the two values using:

preshot_time <- transform(preshot,time=interaction(minute,second,sep=':'))

However, I want to transform them into some sort of minute:second time signature, with the end goal of calculating the time difference in seconds between one row and the next.

I am relatively new to data manipulation in R so any help would be very welcome.

Thanks!

CodePudding user response:

You can create a column representing total seconds, then use dplyr's lag function to calculate the difference from one row to the next.

set.seed(4669)

df <- data.frame(minutes = sample(0:5, size = 5),
                 seconds = sample(1:59, size = 5))

df$elapsedSeconds <- df$minutes * 60   df$seconds

df$diff <- df$elapsedSeconds - dplyr::lag(df$elapsedSeconds)

df

  minutes seconds elapsedSeconds diff
1       0      27             27   NA
2       4       2            242  215
3       5      12            312   70
4       1      45            105 -207
5       3      30            210  105
  •  Tags:  
  • r
  • Related