moving average in r

# Sample data
set.seed(123)
data <- rnorm(10)

# Function to calculate moving average
moving_average <- function(x, k) {
  n <- length(x)
  if (k %% 2 == 0) stop("Only odd values of k are supported.")
  if (k > n) stop("k should be less than or equal to the length of the vector.")

  ma <- numeric(n)
  for (i in 1:n) {
    start <- max(1, i - (k-1)/2)
    end <- min(n, i + (k-1)/2)
    ma[i] <- mean(x[start:end])
  }

  return(ma)
}

# Set the window size for the moving average
window_size <- 3

# Calculate moving average
result <- moving_average(data, window_size)

# Print the original data and the moving average result
print("Original Data:")
print(data)

print(paste("Moving Average (k =", window_size, "):"))
print(result)