Вопрос

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)))
Это было полезно?

Решение 2

Here is a solution using base R function tapply

tapply(df$y, df$date, median)

Update. Judging by your comment above, you need one column for each group? That's also a one-liner:

tapply(df$y, list(df$date, df$group), median)

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top