Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filling an array using for loop in R

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading