## Issue

I would like to generate an array of data matrices, where each matrix will refer to a different scenario, for the purpose of example I have included only 1

```
p13=0.493;p43=0.325;p25=0.335;p35=0.574;p12=0.868
std_e2=sqrt(1-p12^2);std_e2
std_e3=sqrt(1-(p13^2+p43^2));std_e3
std_e5=sqrt(1-(p25^2+p35^2+2*p25*p35*(p13*p12)));std_e5
scenario_1<-matrix(c(3,0,0,0,0),ncol = 5,nrow = 1);scenario_1
genereting_fuction<- function(n,scenario){
sample <- vector("list")
for (i in scenario){
x1=rnorm(n)+scenario[i,1]
x4=rnorm(n)+scenario[i,4]
x2=x1*p12+std_e2*rnorm(n)+scenario[i,2]
x3=x1*p13+x4*p43+std_e3*rnorm(n)+scenario[i,3]
x5=x2*p25+x3*p35+std_e5*rnorm(n)+scenario[i,5]
sample[[i]]=cbind(x1,x2,x3,x4,x5)
colnames(sample[[i]])<-c("x1","x2","x3","x4","x5")
}
sample
}
array_scenari<-array(dim=c(5,5,2));array_scenari
for(j in 1:nrow(scenario_1)){
set.seed(1234)
dati_prova<- sapply(rep(1,5), function(x) genereting_fuction(x,scenario_1),simplify = 'array');dati_prova
dati_prova<-do.call(rbind.data.frame, dati_prova);dati_prova<-as.matrix(dati_prova);dati_prova
dati_prova<-as.matrix(dati_prova)
array_scenari[,,j]<-dati_prova[]
}
```

I can’t understand why it doesn’t work and gives me an error

## Solution

It’s hard to give a concrete answer without a working reproducible example, since your function contains externally defined variables. However, the source of the error is clear. When you create an empty array with `array()`

it has a single fixed dimension:

```
matrix_classification <- array()
dim(matrix_classification)
#> [1] 1
```

And if you try to write into its third dimension you get an error:

```
k <- 1
matrix_classification[, , k] <- "x"
#> Error in matrix_classification[, , k] <- "x": incorrect number of subscripts
```

If you want to write into an array you should define its dimensions first. For example, the following creates an empty 5 x 5 x 5 array:

```
matrix_classification <- array("", dim = c(5, 5, 5))
dim(matrix_classification)
#> [1] 5 5 5
```

And if we want to write a matrix into the *kth* slice we can do:

```
matrix_classification[, , k] <- matrix(sample(letters, 25), nrow = 5)
matrix_classification[,,1]
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] "a" "d" "k" "t" "c"
#> [2,] "f" "b" "n" "m" "s"
#> [3,] "u" "q" "y" "o" "j"
#> [4,] "l" "g" "h" "w" "v"
#> [5,] "r" "i" "e" "p" "z"
```

^{Created on 2022-03-06 by the reprex package (v2.0.1)}

Answered By – Allan Cameron

Answer Checked By – Senaida (BugsFixing Volunteer)