Reputation: 863
I'm trying to find a faster way to run a function, which is looking for the median value for every given day in a time period. Is there a faster way than running Sapply in a for loop?
for(z in unique(as.factor(df$group))){
all[[z]]<- sapply(period, function(x) median(df[x == df$date & df$group==z, 'y']))
}
Sample data:
date<-as.Date("2011-11-01") +
runif( 1000,
max=as.integer(
as.Date( "2012-12-31") -
as.Date( "2011-11-01")))
period<-as.Date(min(df$date):max(df$date), origin = "1970-01-01")
df <- data.frame(date=date, y = rnorm(1000), group=factor(rep(letters[1:4], each=250)))
Upvotes: 2
Views: 145
Reputation: 118799
If I understand right, you want to split by group
and then calculate the median
within each date
. Here's a data.table
solution.
Edit: The problem was with the date
format of your dataset. It seems to report the number of unique elements wrong. So, I had to recast it to POSIXct
format.
df$date <- as.POSIXct(as.character(df$date), format="%Y-%m-%d")
require(data.table)
dt <- data.table(df)
setkey(dt, "date")
dt.out <- dt[, lapply(letters[1:4],
function(x) median(y[group == x])), by = date]
This is identical to Victor's output.
Upvotes: 4