R - Convert seconds in to hours and minutes

I have a data frame like this,

Time ColA Colb
123  A     B

I would like to convert this into a dataframe like this,

Hours Minutes ColA Colb
0      2       A    B

The value in the time column is in the form of Seconds. How to convert this in to hours and minutes?

Upvotes: 2

Views: 19518

Answers (2)

markus
markus

Reputation: 26373

Without additional packages you could make use of %/%, i.e. integer division (similar to A. Suliman's solution in the comments):

df$Hour <- df$Time %/% (60 * 60)
df$Minute <- df$Time %/% 60
df
#  Time ColA Colb Hour Minute
#1  123    A    B    0      2

data

df <- read.table(text = "Time ColA Colb
123  A     B", header = TRUE, stringsAsFactors = FALSE)

Upvotes: 3

Jorge Quintana
Jorge Quintana

Reputation: 840

I reproduce a similar example using the following R code:

library("lubridate")
library("dplyr")

Data <- data.frame(Time = seq(from = 100, to = 1200, by = 100),
                   ColA = rnorm(n = 12, mean = 0, sd = 1),
                   ColB = rnorm(n = 12, mean = 10, sd = 1))

Which generates a DataFrame with three columns, as yours: Time, ColA and ColB. The result looks like this:

   Time    ColA      ColB
1  100  0.3819418  9.793732
2  200 -0.6819604  9.809536
3  300 -1.5910664 10.491511
4  400  0.5091230  8.251863
5  500  1.4298513 10.939813

Based on that you can use lubridate and dplyr libraries the get the result you are looking for, as follows:

Data %>%
    mutate(Hours = hour(seconds_to_period(Time)),
           Minutes = minute(seconds_to_period(Time))) %>%
    select(Hours, Minutes, ColA, ColB)

Which generates the following results:

     Hours Minutes   ColA      ColB
1      0       1  0.3819418  9.793732
2      0       3 -0.6819604  9.809536
3      0       5 -1.5910664 10.491511
4      0       6  0.5091230  8.251863
5      0       8  1.4298513 10.939813

The logic behind that code is the following:

First, you are converting the seconds into a Period (lubridate's object to represent time lapses) using seconds_to_period() function. The result of that looks like this "2H 23M 20S" Then, using hour() and minute() you can extract the units you need, in this case hours and minutes. Finally, you can select the variables you want to keep using select(). I hope it helps!

Upvotes: 7

Related Questions