Search code examples
rplotmodemoving-average

Plotting moving/rolling modal in R


I have a set of data with multiple cases. Each case has a different number of observations. How can I calculate the moving modal and plot the moving modal? My current idea is to create lagging and leading data frames and then use rowModes() with base R to calculate the row modes but I am not sure how I would plot this.

For example, if I want to take the 7-day moving modal of a from the data below, how can I calculate the moving modal and plot it on a figure with a on the y-axis and bas dates on the x-axis?

a <- c(43,82,38,13,54,74,23,73,16,82,10,1,48,93,57,23,23,86,63,23,24,25,26,65,17,23,36,16,90,68,66)
b <- seq(as.Date("2010-12-01"), as.Date("2010-12-31"), by = "days")
testDF <- data.frame(a,b)

Solution

  • You can use rolling functions available from the zoo package. If you want the output of 1-7 values at 7th place, 2-8 at 8th place and so on you can use :

    library(zoo)
    
    testDF$c <- as.numeric(rollapplyr(testDF$a, 7, function(x) {
      tab <- sort(table(x), decreasing = TRUE)
      if(length(unique(tab)) == 1) mean(x)
      else names(tab)[1]
    }, fill = NA))
    

    If you want the output of 1-7 values at 1st place, 2-8 at 2nd place and so on you can use :

    testDF$c <- as.numeric(rollapply(testDF$a, 7, function(x) {
      tab <- sort(table(x), decreasing = TRUE)
      if(length(unique(tab)) == 1) mean(x)
      else names(tab)[1]
    }, fill = NA, align = 'left'))