[R] Applying function to data.frame

Gabor Grothendieck ggrothendieck at gmail.com
Mon Oct 8 19:20:20 CEST 2007


Your function needs to be able to work on vector input, e.g.

transform( y, time=Vectorize(str_to_millis)( as.character(time) ) )

or just do this:

library(chron)
y$time <- 24 * 60 * 60 * 1000 * as.numeric(times(y$time))



On 10/8/07, Rees, David <david.rees at citi.com> wrote:
> Hi,
>
> If I have the following data.frame
>
> >y
>          time val
> 1 08:00:05.834   1
> 2 08:03:13.345   2
> 3 08:10:12.443   3
> >
>
> and the following function which converts the time string to the number
> of milliseconds since midnight
>
> > str_to_millis
> function( s )
> {
> a <- as.numeric( unlist( strsplit(s,":",fixed="TRUE") ) )
> m <- a[1]*3600000 + a[2]*60000 + a[3]*1000
> }
>
> Then to get the time into millis since midnight I am doing this
>
> > transform( y, time=str_to_millis( as.character(time) ) )
>      time val
> 1 28805834   1
> 2 28805834   2
> 3 28805834   3
>
> but this is obviously wrong, as I get all the time values as the first
> element converted rather than each element converted.
>
> Any ideas please?
>
> Many thanks,
> David
>
> ______________________________________________
> 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