Home > OS >  Rolling Sample standard deviation in R
Rolling Sample standard deviation in R

Time:03-10

I wanted to get the standard deviation of the 3 previous row of the data, the present row and the 3 rows after.

This is my attempt:

mutate(ming_STDDEV_SAMP = zoo::rollapply(ming_f, list(c(-3:3)), sd, fill = 0)) %>%

Result

ming_f ming_STDDEV_SAMP
4.235279667 0.222740262
4.265353 0.463348209
4.350810667 0.442607461
3.864739333 0.375839159
3.935632333 0.213821765
3.802632333 0.243294783
3.718387667 0.051625808
4.288542333 0.242010836
4.134689 0.198929941
3.799883667 0.112733475

This is what I expected:

ming_f ming_STDDEV_SAMP
4.235279667 0.225532646
4.265353 0.212776157
4.350810667 0.23658801
3.864739333 0.253399417
3.935632333 0.26144862
3.802632333 0.246259684
3.718387667 0.20514358
4.288542333 0.208578409
4.134689 0.208615874
3.799883667 0.233948429

CodePudding user response:

It doesn't match your output exactly, but perhaps this is what you need:

zoo::rollapply(quux$ming_f, 7, FUN=sd, partial=TRUE)

(It also works replacing 7 with list(-3:3).)

This expression isn't really different from your sample code, but the output is correct. Perhaps your original frame has a group_by still applied?


Data

quux <- structure(list(ming_f = c(4.235279667, 4.265353, 4.350810667, 3.864739333, 3.935632333, 3.802632333, 3.718387667, 4.288542333, 4.134689, 3.799883667), ming_STDDEV_SAMP = c(0.225532646, 0.212776157, 0.23658801, 0.253399417, 0.26144862, 0.246259684, 0.20514358, 0.208578409, 0.208615874, 0.233948429)), class = "data.frame", row.names = c(NA, -10L))
  •  Tags:  
  • r
  • Related