2

I have a vector of values:

[1]   0  0  4  1  0  0 -1  1  1  0 -1  0  0 -2  0  0
[17]  1  2  0  2  0  1  1  1  0  1 -1  0  0  0  0  0
[33]  0  2  0  4 -2  0  0 -1  1  0  0  0 -1 -2  2  0
[49] -1  0 -1  0  3  0  0 -1  1  0  0  0  1 -3  0 -1
[65]  0 -1  0  1  1  0  1 -2  1  1  0  0 -1 -2  0  0
[81]  0  2  0  0  1  1  0  0  0 -1 -2  0 -1 -1 -1 -1
[97]  1  1  0  1

I would like to get the average every 10 steps (the average of the previous 10 numbers at that point), and thus produce a new vector with these averages. Since there are 100 values in the original vector this would give a new vector of length 10 (the 10 averages).

I know I can get access to the number at each 10th point using:

result <- my_vector[seq(1, length(my_vector), 10)]

But I need the average of the 10 previous points at that step, not just the number itself.

Cybernetic
  • 12,628
  • 16
  • 93
  • 132

1 Answers1

2
colMeans(matrix(x, 10))
[1]  0.4  0.7  0.8  0.2  0.0  0.4 -0.4 -0.4 -0.7  0.1

We turn the vector into a matrix with the dimensions matching your desired length and use colMeans to find the mean of each group. We could have also used rowMeans, but since the matrix is populated column-wise by default we would have to add another argument byrow=TRUE and potentially hurt ourselves with all of the extra typing.

We can test our answer by explicitly finding the mean of a few of the subsetted vectors.

#Test
mean(x[1:10])
[1] 0.4
mean(x[11:20])
[1] 0.7

Data

x <- c(0, 1, 0, -1, 0, 0, 0, 2, 2, 0, -1, 2, 4, 0, 0, -1, 0, 0, 1, 
2, 4, 0, 1, 0, 0, 0, -2, 3, 1, 1, 0, 1, 0, 0, 0, 1, -1, 1, 0, 
0, 1, 0, 1, 1, -1, -1, -2, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 
-1, -1, -1, 0, 0, 0, -2, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, -1, -1, 
-2, 0, -2, -3, -2, -1, 0, 0, 2, 0, 0, -1, 0, 0, 0, -1, 0, -1, 
1, 1, 0, 1)
Pierre L
  • 28,203
  • 6
  • 47
  • 69