[R] Problem with POSIXct in ave

Sasha Hafner
Fri, 20 Aug 2010 14:56:57 -0000

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.

Thanks,
   Sasha

	[[alternative HTML version deleted]]