[R] Problem with POSIXct in ave

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 20 21:09:00 CEST 2010


On Fri, Aug 20, 2010 at 10:56 AM, Sasha Hafner <sdhafner at gmail.com> wrote:
> Hi,
>
> I am having trouble using the ave function with a POSIXct object. For
> example:
>
> x<-Sys.time()+0:9*3600
> dat<-data.frame(id=rep(c('a','
> b','c'),each=10),dt=rep(x,3),i=rep(1:10,3))
> dat
>
> # This is what I want to do:
> dat$time.elapsed<-unsplit(lapply(split(dat$dt,dat$id),function(x)
> x-x[1]),f=dat$id)
> dat
>
> # The above code does the trick, but from the standpoint of simplicity, the
> ave function seems to be perfect for this problem:
> ave(dat$dt,dat$id,FUN=function(x) difftime(x,x[1]))
> # Above doesn't work, returns: Error in as.POSIXct.default(value) : do not
> know how to convert 'value' to class "POSIXct"
>
> # Same error message with this:
> ave(dat$dt,dat$id,FUN=function(x) x - x[1])
>
> # But the following (using numeric data instead of POSIXct) does work:
> ave(dat$i,dat$id,FUN=function(x) x-x[1])
>
> # Problem seems to be in an assignment statement with split on the lhs
> split(dat$dt,dat$id)<-lapply(split(dat$dt,dat$id),function(x) x-x[1])
>
> # Because rhs works:
> lapply(split(dat$dt,dat$id),function(x) x-x[1])
>
> # And this works without assignment
> split(dat$dt,dat$id)
>
> Does anyone have any ideas about how to get ave to work with POSIXct
> objects, or the cause of this (apparent) problem? I am using R v. 2.11.1.
>

If dat is sorted by id and dt (as is the case in your example) then try:

   dat$dt <- with(dat, dt - dt[match(id, id)])



More information about the R-help mailing list