# Create a rolling mean column by displaying means to corresponding values in R data frame.

To create a rolling mean column by displaying means to corresponding values in R data frame, we can use ave function with rep function.

For Example, if we have a data frame called df that contains a numerical column say X then we can create a rolling mean column for every 5 values by using the below mentioned command −

df$Rolling_M_5<-ave(df$X,rep(1:(nrow(df)/5),each=5),FUN=function(x){mean(x)})

## Example 1

Following snippet creates a sample data frame −

x<-rnorm(20)
df1<-data.frame(x)
df1

The following dataframe is created

x
1  0.54695282
2 -2.14433689
3  0.60614761
4  1.42172678
5  1.45355367
6  0.27851529
7  0.43483588
8  3.10239061
9  1.26224723
10 -0.04519611
11 -1.22239574
12  1.04256580
13 -0.44032532
14  1.41468774
15 -0.15795517
16 -0.18538886
17 -0.82291711
18 -0.56077655
19  1.75063692
20  0.23353949

To create a rolling mean column in df1 with mean displayed corresponding to each value on the above created data frame, add the following code to the above snippet −

x<-rnorm(20)
df1<-data.frame(x)
df1$Rolling_Mean_4<-ave(df1$x,rep(1:(nrow(df1)/4),each=4),FUN=function(x){mean(x)})
df1

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

x    Rolling_Mean_4
1  0.54695282 0.1076226
2 -2.14433689 0.1076226
3  0.60614761 0.1076226
4  1.42172678 0.1076226
5  1.45355367 1.3173239
6  0.27851529 1.3173239
7  0.43483588 1.3173239
8  3.10239061 1.3173239
9  1.26224723 0.2593053
10 -0.04519611 0.2593053
11 -1.22239574 0.2593053
12  1.04256580 0.2593053
13 -0.44032532 0.1577546
14  1.41468774 0.1577546
15 -0.15795517 0.1577546
16 -0.18538886 0.1577546
17 -0.82291711 0.1501207
18 -0.56077655 0.1501207
19  1.75063692 0.1501207
20  0.23353949 0.1501207

## Example 2

Following snippet creates a sample data frame −

y<-rpois(20,10)
df2<-data.frame(y)
df2

The following dataframe is created

y
1  6
2 11
3 12
4 15
5  5
6 12
7 11
8 15
9 13
10  9
11  9
12  4
13  9
14 10
15  7
16  8
17  6
18  9
19 13
20 11

To create a rolling mean column in df2 with mean displayed corresponding to each value on the above created data frame, add the following code to the above snippet −

y<-rpois(20,10)
df2<-data.frame(y)
df2$Rolling_Mean_2<-ave(df2$y,rep(1:(nrow(df2)/2),each=2),FUN=function(x){mean(x)})
df2

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

y    Rolling_Mean_2
1  6  8.5
2 11  8.5
3 12 13.5
4 15 13.5
5  5  8.5
6 12  8.5
7 11 13.0
8 15 13.0
9 13 11.0
10  9 11.0
11  9  6.5
12  4  6.5
13  9  9.5
14 10  9.5
15  7  7.5
16  8  7.5
17  6  7.5
18  9  7.5
19 13 12.0
20 11 12.0