Loop over matrix and choose row depending on variable number - R

Viewed 37

I have a combination matrix which consists of five variables (A,B,C,D,E), each with five possible values, providing a total of 3125 possible combinations. A smaller incomplete example is below for two variables and five values (i.e. a 25 combination matrix)?

A B
A1 B1
A1 B2
A1 B3
A1 B4
A1 B5
A2 B1
A2 B2
A2 B3
A2 B4
A2 B5
A3 B1

and so the complete table would have 25 different rows of each combination.

I am running 3125 forecasts and for each run (let's call it FCST_NUM) I would like to assign each variable (i.e. A,B,C,D,E) to a row in the matrix. So in forecast one (i.e. FCST_NUM=1) variables A,B,C,D,E use the values in the first row of the matrix, in forecast two (i.e. FCST_NUM=2) variables A,B,C,D,E use the values of the second row and so on.

In the code FCST_NUM would start from 1 and I would add 1 for each iteration. How could I define variables A,B,C,D,E so that each get assigned to the correct value in the row of the matrix based on the FCST_NUM (e.g. when FCST_NUM = X, values A,B,C,D,E is equal to row(,X) of matrix).

R code to produce matrix example is below:

N   <- 5 
vec <- c(0.2,0.6,1,1.4,1.8)
lst <- lapply(numeric(N), function(x) vec)
Matrix <- as.matrix(expand.grid(lst))
1 Answers

It was actually easier than I thought in R. It was just a case of setting FCST_NUM to whatever the number of the run was and then indexing from the matrix as below.

# create matrix of possible combinations 
N   <- 5 
vec <- c(0.2,0.6,1,1.4,1.8)
lst <- lapply(numeric(N), function(x) vec)
Matrix <- as.matrix(expand.grid(lst))

# define FCST_NUM
FCST_NUM = 1  

# assign value to each variable based on FCST_NUM
A <- Matrix[FCST_NUM,1]
B <- Matrix[FCST_NUM,2]
C <- Matrix[FCST_NUM,3]
D <- Matrix[FCST_NUM,4]
E <- Matrix[FCST_NUM,5]

So if FCST_NUM was 1, then variables A,B,C,D,E would be assigned to the values on the 1st row of the matrix.

Related