0

I have huge size data frame with several columns: 1) gridID 2) species code(SPCD) 3) related values(index) 4) related values(index1) and 5) latitude.

but GridID is not unique numbers as GridID has multiple SPCD For example,

tbl = data.frame(gridID=c(1,1,1,1,1,2,2,2,2,2),
  SPCD=c(1,2,3,4,5,1,2,3,4,5),
  INDEX=c(2,2,4,3,2,3,4,2,3,24),
  INDEX1=c(1,4,3,5,4,2,34,6,4,3),
  LAT=c(34.1,34.4,35,35.2,35.4,36,37,36.4,46,34))

I want to find moving average by +/-0.5 latitudinal band group by SPCD.

what I did was

> #Generating a sequence of latitudinal bands   
> lat_seq<-seq(from=26, to=49,by=.5)   
> spcd_list<-unique(tbl$SPCD)
> # Creating a blank array to place the data in   
> bands<-array(dim=c(length(lat_seq),nrow(spcd_list)+1,2))  
> bands[,1,]<-lat_seq
> 
> # Finding the averages for each moving latitudinal band   
> for(i in 1:nrow(spcd_list)){
>     for(j in 1:length(lat_seq)){
>       lat_min<-lat_seq[j]-.5
>       lat_max<-lat_seq[j]+.5
>       
>       #Defining the band width
>         band<-subset(tbl,tbl$LAT>=lat_min & tbl$LAT<=lat_max)
>       
>       # Selecting the species of interest and 
>       #   calculating average abundace measures
>         species<-subset(band,band$SPCD==spcd_list[i,1])
>       
>       bands[j,i+1,1]<-mean(species$index)
>       bands[j,i+1,2]<-mean(species$index1)
> 
>     }   }

above approach works but takes so much time. I wonder if there's better way to do this. zoo and rollapply is one I am learning. but couldn't make it work.

kclick
  • 45
  • 8
  • You mean `zoo::rollapply()` not `plyr`. What does 'but failed mean? a) 'it errored out' (if so, paste both your code and the error) b) out-of-memory or c) 'I couldn't figure out how to code with rollapply'? – smci May 20 '14 at 18:40
  • 1
    The code does not work. It gives errors. Please fix. – G. Grothendieck May 20 '14 at 19:25
  • Isn't the longitude relevant here? I'm just thinking in a spatial approach instead of a vectorized one. You want the mean index and mean index1 per species right? – Paulo E. Cardoso May 20 '14 at 19:34
  • yes. I want rolling mean for both indices per species. And longitude is not considered here. Just latitudinal band. – kclick May 20 '14 at 20:13

0 Answers0