Trouble with custom function in R to calculate rolling averages - unexpected output
I'm performance testing and I'm having trouble with I'm integrating two systems and I need help solving I'm trying to create a custom function in R that calculates the rolling average of a numeric vector, but I'm working with unexpected output. My implementation seems to work for small vectors, but when I use larger datasets, the results deviate significantly from what I expect. Here's the function I've written: ```r rolling_average <- function(x, n) { if (length(x) < n) return(NA) result <- numeric(length(x) - n + 1) for (i in 1:(length(x) - n + 1)) { result[i] <- mean(x[i:(i + n - 1)]) } return(result) } ``` I test it with the following example: ```r data <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) rolling_average(data, 3) ``` This gives me the expected output: `c(2, 3, 4, 5, 6, 7, 8)`. However, when I try it with a larger dataset: ```r large_data <- rnorm(1000) rolling_average(large_data, 50) ``` The output seems much less stable and sometimes returns NA values unexpectedly, even when the window size is valid. I’ve tried debugging by adding print statements within the loop, but it doesn't reveal anything unusual. Is there something I'm missing in my implementation, particularly when it comes to handling larger datasets? Any suggestions on how to improve the performance and reliability of this function would be greatly appreciated. I'm using R version 4.1.0. Am I missing something obvious?