[R] Adding duration (hh:mm:ss)\Converting factor column into duration class

R. Michael Weylandt michael.weylandt at gmail.com
Thu Mar 29 17:43:48 CEST 2012


Factor -> numeric is tricky sometimes: you need to do this
as.numeric(as.character(x))

but that's not going to work for you here because you don't really
want numbers.

Instead try something like this (untested though):

parseDuration <- function(t1, t2){
    t1 <- as.numeric(unlist(strsplit(as.character(t1), ":")))
    t2 <- as.numeric(unlist(strsplit(as.character(t2), ":")))
    new_duration(hour = t1[1] - t2[1], minute = t1[2] - t2[2], second
= t1[3] - t2[3])
}

as.duration(apply(x, 1, function(m) parseDuration(m[1], m[2])))

This could likely be made cleaner -- I don't know lubridate well.

Hope this helps,

Michael

On Thu, Mar 29, 2012 at 7:57 AM, drr <daniel.roj at wp.pl> wrote:
> Hi All,
>
> I have a data frame:
>
>              Time1    Time2
>     1  176:46:10    41:48:06
>     2  171:28:57    61:19:10
>     3  178:25:15    34:05:35
>     4   74:04:20     25:01:55
>     5  136:11:20    37:59:32
>     6  138:17:17    30:22:27
>     7  183:04:48    29:25:02
>     8  179:35:01    19:29:44
>
>> str(df)
> 'data.frame':   8 obs. of  2 variables:
>  $ Time1: Factor w/ 583 levels "","00:00:01",..: 574 573 575 583 565 566 579
> 577
>  $ Time2: Factor w/ 1298 levels "00:00:00","00:00:01",..: 1292 1297 1288
> 1281 1290 1286 1284 1279
>
> I would like to make calculations (adding, summing) on this data. How do I
> transform those factors into duration data (in format hh:mm:ss).  I have
> already found *lubridate* package but it does not work with factors. I tried
> to convert as numeric, but it never works for me.
>
> How do I do that?
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Adding-duration-hh-mm-ss-Converting-factor-column-into-duration-class-tp4515210p4515210.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list