1

I have a df with a single column (col1)

df <- data.frame(col1 = c(96, 56, 53, 63, 70, 65, 72, 
                          111, 65, 58, 59, 74, 57, 70, 
                          89, 60, 60, 52, 65, 58, 84, 
                          54, 55, 51, 72))

I want to take the average of 7 values at a time and move a value down at a time to get a table like this below. So each value in week_avg is average of the last 7 values of the col1

col1   week_avg
96  
56  
53  
63  
70  
65  
72     68
111    70
65     71
58     72
59     72
74     72
57     71
70     71
89     67
60     67
60     67
52     66
65     65
58     65
84     67
54     62
55     61
51     60
72     63
Zmnako Awrahman
  • 538
  • 7
  • 19

1 Answers1

2

Using zoo and dplyr:

library(dplyr)
library(zoo)

df <- df %>% mutate(moving_average = round(rollmeanr(col1, 7, fill = NA)))


> df
   col1 moving_average
1    96             NA
2    56             NA
3    53             NA
4    63             NA
5    70             NA
6    65             NA
7    72             68
8   111             70
9    65             71
10   58             72
11   59             71
12   74             72
13   57             71
14   70             71
15   89             67
16   60             67
17   60             67
18   52             66
19   65             65
20   58             65
21   84             67
22   54             62
23   55             61
24   51             60
25   72             63
f.lechleitner
  • 3,554
  • 1
  • 17
  • 35
  • 1
    Thanks, I used a combination of your answer. This code gave me desired outcome: `df <- df %>% mutate(moving_average = rollmeanr(col1, 7, fill = NA)) ` – Zmnako Awrahman Jan 04 '18 at 15:18