简体   繁体   English

循环矩阵并根据变量数选择行 - R

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

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、B、C、D、E)组成,每个变量都有五个可能的值,总共提供 3125 种可能的组合。 A smaller incomplete example is below for two variables and five values (ie a 25 combination matrix)?下面是一个较小的不完整示例,用于两个变量和五个值(即 25 组合矩阵)?

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

and so the complete table would have 25 different rows of each combination.因此,完整的表格将有 25 个不同的行,每个组合。

I am running 3125 forecasts and for each run (let's call it FCST_NUM) I would like to assign each variable (ie A,B,C,D,E) to a row in the matrix.我正在运行 3125 次预测,对于每次运行(我们称之为 FCST_NUM),我想将每个变量(即 A、B、C、D、E)分配给矩阵中的一行。 So in forecast one (ie FCST_NUM=1) variables A,B,C,D,E use the values in the first row of the matrix, in forecast two (ie FCST_NUM=2) variables A,B,C,D,E use the values of the second row and so on.因此在预测一个(即 FCST_NUM=1)变量 A,B,C,D,E 中使用矩阵第一行中的值,在预测两个(即 FCST_NUM=2)变量 A,B,C,D,E使用第二行的值,依此类推。

In the code FCST_NUM would start from 1 and I would add 1 for each iteration.在代码中 FCST_NUM 将从 1 开始,我会为每次迭代添加 1。 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 (eg when FCST_NUM = X, values A,B,C,D,E is equal to row(,X) of matrix).我如何定义变量 A、B、C、D、E 以便根据 FCST_NUM 将每个变量分配给矩阵行中的正确值(例如,当 FCST_NUM = X 时,值 A、B、C、D、E等于矩阵的行(,X))。

R code to produce matrix example is below: R 代码生成矩阵示例如下:

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))

It was actually easier than I thought in R.它实际上比我在 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.这只是将 FCST_NUM 设置为任何运行次数然后从矩阵索引如下的情况。

# 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.因此,如果 FCST_NUM 为 1,则变量 A,B,C,D,E 将分配给矩阵第一行的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM