Home > Mobile >  Calculate Sample Variance in window 2 sec before to current sec through 3 seconds after current seco
Calculate Sample Variance in window 2 sec before to current sec through 3 seconds after current seco

Time:12-09

This is what am trying to do:

Time value
00:00 12
00:01 6
00:02 8
00:03 12
00:04 11
00:05 6
00:06 13
00:07 12
00:08 12

and i want sample variance and result like:

Time value samp_vars
00:00 12 NA
00:01 6 NA
00:02 8 24.1666
00:03 12 12.8
00:04 11 6.8
00:05 6 3.0667
00:06 13 3.7
00:07 12 3.5833
00:08 12 0.333

I tried doing this: df$samp_vars <- rollapply(df$value, list(c(-2,0,3)), var, fill = NA)

but my variance sample was not correct. I am not an expert in R so i will appreciate the help. Thanks!

CodePudding user response:

I make the expected values to be NA, NA, 8.166, 9.466, 7.466, 6.400, NA, NA, NA — not as you have in the question. For example, at 00:02

var(c(12,6,8,12,11,6))

To get those values, simply alter your existing code to use a sequence of the right integers using : — at the moment you are getting the variance at the current row, the row two steps back and the row three steps forward, not all in between.

zoo::rollapply(data$value, list(-2:3), var, fill = NA)

The -2:3 is making a vector of the integers c(-2, -1, 0, 1, 2, 3) for you.

  •  Tags:  
  • r
  • Related