简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM