On Aug 20, 2010, at 10:56 AM, Sasha Hafner 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]))
Try:
dat$elapsed <- ave(dat$dt,dat$id,FUN=function(x)
as.POSIXct(as.numeric(x,x[1]), origin="1970-01-01"))
dat
I don't know why difftime doesn't work, but the above uses the "naked"
numeric time in seconds and then restores the DateTime atrributes.
--
David.
# 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]]
______________________________________________
R-help@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.
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@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.