Reputation: 69
Guys I have the following code below where I simulate a number of poisson values and for each value, simulate n exponential values and allocate in the first n rows of the same column in the 'matrix' dataframe. Where ind
are the values obtained in each column of p that will be used to fill the first ind
rows of each 'matrix' column, tamanho
is the number of rows and cenarios
is the number of columns.
p = matrix(data=rpois(1*cenarios, p*tamanho), nrow=1, ncol=cenarios)
matriz = matrix(NA, tamanho, cenarios)
matriz[ind] = rexp(nrow(ind), rate = 1/media)
So in case if my p is
4 3 0 5 ...
My matrix must be
x11 x12 0 x14 ...
x21 x22 0 x24 ...
x31 x32 0 x34 ...
x41 0 0 x44 ...
0 0 0 x54 ...
0 0 0 0 ...
. . . . ...
. . . . ...
. . . . ...
Can anyone help me do this? Unfortunately my code is not producing this result and I don't know how to get it there. Thank you!
Upvotes: 0
Views: 91
Reputation: 8844
Is this what you want?
cenarios <- 5
tamanho <- 6
media <- 10
p <- 0.5
get_idx <- function(p) {
dim(p) <- NULL
cbind(
row = unlist(lapply(p, seq_len)),
col = inverse.rle(list(lengths = p, values = seq_along(p)))
)
}
set.seed(14)
p = matrix(data=rpois(1*cenarios, p*tamanho), nrow=1, ncol=cenarios)
matriz = matrix(0, p[1L, max.col(p)], cenarios)
ind = get_idx(p)
matriz[ind] = rexp(nrow(ind), rate = 1/media)
> matriz
[,1] [,2] [,3] [,4] [,5]
[1,] 0.2294774 12.197561 11.055460 4.998411 0.4666982
[2,] 2.9696347 1.135306 3.467462 2.379091 3.7448796
[3,] 0.0000000 5.127104 2.432433 12.324723 23.3540920
[4,] 0.0000000 0.000000 13.716225 0.000000 6.2265665
[5,] 0.0000000 0.000000 2.353816 0.000000 14.8491943
[6,] 0.0000000 0.000000 3.805390 0.000000 0.8669793
[7,] 0.0000000 0.000000 0.000000 0.000000 1.0776727
Upvotes: 1