Home > Blockchain >  Filling an array using for loop in R
Filling an array using for loop in R

Time:09-29

I would like to fill an array with different values of prob using a forloop in R. The code I have now:

prob = c(0.05, 0.06, 0.07, 0.08, 0.09)

for (i in prob) {
trans_mat <- array(0, dim = c(3, 3, 5))
trans_mat[1, 2, 1:length(i)] <- i
}

This gives 5 matrixes where only in the first matrix 0.09 is filled in. How do I get 5 matrix where the first one has 0.05, the second one 0.06 and so on for all 5 matrixes?

CodePudding user response:

You need to create trans_mat first and write into each slice of it:

prob <- c(0.05, 0.06, 0.07, 0.08, 0.09)

trans_mat <- array(0, dim = c(3, 3, 5))

for (i in seq_along(prob)) trans_mat[,,i] <- prob[i]

result:

trans_mat
#> , , 1
#> 
#>      [,1] [,2] [,3]
#> [1,] 0.05 0.05 0.05
#> [2,] 0.05 0.05 0.05
#> [3,] 0.05 0.05 0.05
#> 
#> , , 2
#> 
#>      [,1] [,2] [,3]
#> [1,] 0.06 0.06 0.06
#> [2,] 0.06 0.06 0.06
#> [3,] 0.06 0.06 0.06
#> 
#> , , 3
#> 
#>      [,1] [,2] [,3]
#> [1,] 0.07 0.07 0.07
#> [2,] 0.07 0.07 0.07
#> [3,] 0.07 0.07 0.07
#> 
#> , , 4
#> 
#>      [,1] [,2] [,3]
#> [1,] 0.08 0.08 0.08
#> [2,] 0.08 0.08 0.08
#> [3,] 0.08 0.08 0.08
#> 
#> , , 5
#> 
#>      [,1] [,2] [,3]
#> [1,] 0.09 0.09 0.09
#> [2,] 0.09 0.09 0.09
#> [3,] 0.09 0.09 0.09

EDIT

It's not clear exactly what your expected output is here. If you only want the cell [1, 2] filled in each matrix, with the remainded being blank, your loop would be

for (i in seq_along(prob)) trans_mat[1, 2, i] <- prob[i]

Created on 2022-09-29 with reprex v2.0.2

CodePudding user response:

You can also do it in one go:

Only the first element of the second column.

trans_mat <- array(0, dim = c(3, 3, 5))
trans_mat[1, 2, ] <- c(0.05, 0.06, 0.07, 0.08, 0.09)
, , 1

     [,1] [,2] [,3]
[1,]    0 0.05    0
[2,]    0 0.00    0
[3,]    0 0.00    0

, , 2

     [,1] [,2] [,3]
[1,]    0 0.06    0
[2,]    0 0.00    0
[3,]    0 0.00    0

, , 3

     [,1] [,2] [,3]
[1,]    0 0.07    0
[2,]    0 0.00    0
[3,]    0 0.00    0

, , 4

     [,1] [,2] [,3]
[1,]    0 0.08    0
[2,]    0 0.00    0
[3,]    0 0.00    0

, , 5

     [,1] [,2] [,3]
[1,]    0 0.09    0
[2,]    0 0.00    0
[3,]    0 0.00    0

The full matrix filled with the same number:

array(rep(c(0.05, 0.06, 0.07, 0.08, 0.09), each = 3*3), dim = c(3, 3, 5))

output

, , 1

     [,1] [,2] [,3]
[1,] 0.05 0.05 0.05
[2,] 0.05 0.05 0.05
[3,] 0.05 0.05 0.05

, , 2

     [,1] [,2] [,3]
[1,] 0.06 0.06 0.06
[2,] 0.06 0.06 0.06
[3,] 0.06 0.06 0.06

, , 3

     [,1] [,2] [,3]
[1,] 0.07 0.07 0.07
[2,] 0.07 0.07 0.07
[3,] 0.07 0.07 0.07

, , 4

     [,1] [,2] [,3]
[1,] 0.08 0.08 0.08
[2,] 0.08 0.08 0.08
[3,] 0.08 0.08 0.08

, , 5

     [,1] [,2] [,3]
[1,] 0.09 0.09 0.09
[2,] 0.09 0.09 0.09
[3,] 0.09 0.09 0.09
  • Related