For each time point in my data frame, I have any where from 2 to 4 measurements. I want to calculate the moving average, so that for a given time point I have one value that is the average of all measurements for that time point + the time point before and the time point after.
cellcounts <-c(80, 188, 206, 162, 106, 90, 85, 109, 87, 94, 86, 196, 132, 135, 84, 122, 67, 88, 81, 121, 9, 93, 117, 91, 108, 103, 119, 100, 18, 98, 93, 119, 140, 160, 101, 82, 111, 103, 28, 72, 144, 85, 1)
time <-c(-2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -2.7, -2.8, -2.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.6, -3.9, -3.0, -3.1, -3.2, -3.3, -3.4, -3.5, -3.7, -2.5, -2.6, -2.9, -3.0, -3.2, -3.3, -3.4, -3.5, -3.7, -3.8, -2.5, -2.6, -3.7, -3.8, -3.9)
df <- data.frame(cellcounts, time)
df <- df[order(df$time),]
df
zoo::rollapply(df, width = 3, FUN = mean, align = "center", fill = NA)
In base R:
Or, averaging only 2 time steps at the endpoints: