Reputation: 956
Each year, a number of people move into a village. This is represented by the following vector:
x <- c(304, 213, 688, 400, 122, 449, 143, 90)
Each year, 10% of people leave the village. The proportion of people from each cohort remaining after a certain number of years is (for 10 years):
decay <- (1-0.1)^(0:10)
Using R, how do I combine x
and decay
to construct a matrix showing the number of people living in the village each year from each cohort?
Here is an example of the result I am aiming for:
Upvotes: 0
Views: 56
Reputation: 269654
Let m be a diagonal matrix with x along the diagonal. Then
m <- diag(x)
t(x * .9^(col(m)-row(m))) * (col(m) <= row(m))
giving:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 304.0000 0.0000 0.0000 0.00 0.000 0.00 0.0 0
[2,] 273.6000 213.0000 0.0000 0.00 0.000 0.00 0.0 0
[3,] 246.2400 191.7000 688.0000 0.00 0.000 0.00 0.0 0
[4,] 221.6160 172.5300 619.2000 400.00 0.000 0.00 0.0 0
[5,] 199.4544 155.2770 557.2800 360.00 122.000 0.00 0.0 0
[6,] 179.5090 139.7493 501.5520 324.00 109.800 449.00 0.0 0
[7,] 161.5581 125.7744 451.3968 291.60 98.820 404.10 143.0 0
[8,] 145.4023 113.1969 406.2571 262.44 88.938 363.69 128.7 90
Alternately use a double for loop:
m <- diag(x)
for(i in seq_along(x))
for(j in seq_along(x))
m[i, j] <- (x[j] * .9 ^ (i - j)) * (j <= i)
Upvotes: 2