I was dealing with a vector of timestamps that were formatted as 'seconds since the epoch' and what I wanted was to limit that vector to weekend timestamps only.
My naive approach was to construct a simple loop over the values and apply a function to each element. I was only dealing with about 20,000 elements but the time to do this was painfully slow - roughly 20 seconds - so I started investigating an apply-like approach. R provides several ways to do this depending on the input/output requirements: lapply, sapply, and vapply. All three resulted in behavior similar to the simple loop.
The function to test for weekend-ness is as follows:
is.weekend <- function(x) {
tm <- as.POSIXlt(x,origin="1970/01/01")
format(tm,"%a") %in% c("Sat","Sun")
}
Looping:
use.sapply <- function(data) {
data[sapply(data$TIME,FUN=is.weekend),]
}
system.time(v <- use.sapply(csv.data))
user system elapsed
19.456 6.492 25.951
Vectorized:
use.vector <- function(data) {
data[is.weekend(data$TIME),]
}
system.time(v <- use.vector(csv.data))
user system elapsed
0.032 0.020 0.052
Duly noted.
No comments :
Post a Comment