Code Optimization for Downsampling

I have a table like this that is flyTracesFiltered.

     Time    Right     Left
1 0.000000000 18.21980 30.98789
2 0.009222031 22.15157 37.18590
3 0.022511959 25.63218 42.49231
4 0.029854059 28.43851 46.57811
5 0.039320946 30.43885 49.29414
6 0.052499056 31.60561 50.67852

What I wanted to do was reduce the time. That is, I want to average all the values ​​over a certain period in order to reduce the number of samples. In my case, I used average values ​​of 0.05 seconds (20 Hz). The function I did looked like this:

flyDataDownsampleTime <- function(flyTracesFiltered, samplePeriod) {

  AvgRight<-NULL
  FlyDataRight<-NULL
  AvgLeftt<-NULL
  FlyDataLeft<-NULL
  AvgTime<-NULL
  FlyDataTime<-NULL


  for (i in seq(0,ceiling(max(flyTracesFiltered$Time)),samplePeriod)){

  AvgRight <-mean(flyTracesFiltered$Right[flyTracesFiltered$Time>=i & flyTracesFiltered$Time <= (i+samplePeriod)])  
  FlyDataRight<-c(FlyDataRight,AvgRight)

  AvgLeft <-mean(flyTracesFiltered$Left[flyTracesFiltered$Time>=i & flyTracesFiltered$Time <= (i+samplePeriod)])  
  FlyDataLeft<-c(FlyDataLeft,AvgLeft)

  AvgTime <-mean(flyTracesFiltered$Time[flyTracesFiltered$Time>=i & flyTracesFiltered$Time <= (i+samplePeriod)])  
  FlyDataTime<-c(FlyDataTime,AvgTime)
}
flyTracesDownTime <- data.frame("Time" = FlyDataTime, "Right" = FlyDataRight, "Left" = FlyDataLeft)

return(flyTracesDownTime)
}

I wanted to ask if there is a way to improve this, because large data frames require a lot of time. I am having problems implementing family functions when I need iterations, as in this case (due to indexing). I also read about the Vectorize function, but I don't know if this can make the code more efficient. Any suggestions?

+4
1

, , group_num

flyTracesFiltered$group_num <- floor(flyTracesFiltered$Time/0.05)

0.05 - , . -

flyTracesFiltered2 = aggregate(flyTracesFiltered$Right,
                     list(group_num=flyTracesFiltered$group_num), mean)

group_num.

() .

+2

Source: https://habr.com/ru/post/1619034/


All Articles