Assume I have longitudinal data (e.g. 21 countries' gdp over 5 years) with 2 variables of the same scale. data is sorted as follows

| Country-year | x1 | x2 |
| --- | --- | --- |
| USA-1 | 50 | 2 |
| USA-2 | 47 | 1.5 |
| ... | ... | ... |
| USA-5 | 52 | 1.9 |
| UK-1 | 63 | 2 |
| ... | ... | ... |
| UK-5 | 41 | 3 |
| ... | ... | ... |

```
n = 21
m = 5
N = n * m
set.seed(123)
x <- MASS::mvrnorm(N, rep(0,2), diag(2))

```

I want to do two things:

* First, calculate the mean country-wise
* Second, calculate the mean year-wise

For the first task, I have the following code

```
x_barbar <- NULL
k = 1
for(i in 1:n){
 x_barbar[i] <- mean(x[k:(k + (m - 1)), ])
 k = k + m
}

```

How can I optimize my code for the first task and figure out a code to do the second task?

Your help is appreciated.