0

I have daily data (4011 days) together with indicator (1-weekdays, 2-weekend). I want to find weekly maxima with the corresponding indicator. For example (let say) the data is:

mydat <- matrix(c(0.027,0.034,0.019,0.021,0.026,0.024,0.058,0.026,0.064,
     0.066,0.026,0.101,0.069,0.054,rep(2,2),rep(1,5),rep(2,2),rep(1,5)), ncol=2)

I have try with the following code. I manage to get the maximum sequences (in this case, weekly maxima) but I dont want maximum sequences in indicator. Here is the code

week.max <- function(vec){    
   if(length(vec[is.na(vec)]) == 7){       
   return(NA)     
   } 
   else{
     return(max(vec, na.rm = T))
   } 
}

max.week.dat <- apply(mydat, 2, function(x) tapply(x, rep(1:(length(x)/7), 
  each=7, len=length(x)), week.max)) 

and the result

matrix(c(0.058,0.101,2,2),ncol=2)

I want the output like this:

matrix(c(0.058,0.101,1,1),ncol=2)

Many thanks in advance.

lyn
  • 61
  • 4
  • Is there any specific reason you want the second column to be `c(1,1)` not `c(1,2)`?, which would indicate the week number? – mnel May 23 '12 at 04:42
  • I want the second column give the value which have the same row where the max in first column is obtained. As in my example, the max values in first column are from rows 7 and 12, so the corresponding values for 2nd column in rows 7 and 12 is 1 and 1 respectively. I know my code will give max value for each column but I dont know how to adjust it. – lyn May 23 '12 at 04:57

1 Answers1

1

Here is the data (with an extra day in the third week)

mydat <- data.frame(value = c(0.027,0.034,0.019,0.021,0.026,0.024,0.058,0.026,0.064,
     0.066,0.026,0.101,0.069,0.054,0.95), ind = c(rep(2,2),rep(1,5),rep(2,2),rep(1,5),2))

Your function

week.max <- function(vec){    
  if(length(vec[is.na(vec)]) == 7){       
return(NA)     
 } 
 else{
return(max(vec, na.rm = T))
 } 
}

Add the week information

mydat$week <- c(rep(1:2,each=7),3)

Use the same solution as for here

library(plyr)
ddply(mydat, .(week), subset, subset = value==week.max(value), select = -week)
Community
  • 1
  • 1
mnel
  • 113,303
  • 27
  • 265
  • 254