I want to fill a 2x2 matrix for every row (N = 500) of my data.
N = 500 # Number of observations
S = 2 # Number of rows and columns of the data
Let's assume this is my example data. It contains 500 observations of 5 covariates.
X <- data.frame(matrix(rexp(2500, rate=.1), ncol=5))
X
From my model, I retrieved 2 coefficients for each covariate.
beta <- data.frame(matrix(rexp(10, rate=.1), ncol=5))
beta
Because I want to fill a 2x2 matrix for each row of my data, I create an output array of size 22n.
output_array = array(NA, dim = c(S,S,N))
Now I want to fill this array in the following way:
- If the position in the 2x2 matrix is [1,1] or [2,2], I want it to be 1.
- If the position in the matrix is [1,2], I want it to be the product of the coefficients in the first row of beta and the first row of X
- If the position in the matrix is [2,1], I want it to be the product of the coefficients in the second row of beta and the first row of X
I want to follow this procedure for all 500 rows of data (...so it goes through the rows), resulting in 500 2x2 matrices (one for each row of data).
My idea was the following function, but it seems that there is a mismatch in dimensions and I'm doing something wrong.
for(t in 1:N){
betarow = 1
for (k in 1:S){
for (j in 1:S){
if(k == j){
output_array[t,k,j] = 1;
} else {
output_array = X1[t,]*beta[betarow]
betarow = betarow + 1;
}
}
}
}