[英]Loop to create a specific matrix in R
I am not a programmer (in fact I am an economist). 我不是程序员(实际上我是经济学家)。 So, please, be generous with your answer.
因此,请大方回答。 I've just started to learn R - I've already read some tutorials about loops but I'm still stuck in this problem.
我刚刚开始学习R-我已经阅读了一些有关循环的教程,但是我仍然陷于这个问题。
My problem is: I need to create the matrix below using loop in R. 我的问题是:我需要使用R中的循环创建下面的矩阵。
$$
\begin{bmatrix}
0.1 & 0.9 & 0 & 0 & 0\\
0.1 & 0 & 0.9 & 0 & 0\\
0 & 0.1 & 0 & 0.9 &0 \\
0 & 0 & 0.1 & 0 &0.9 \\
0 & 0 & 0 & 0.1 & 0.9
\end{bmatrix}
$$
I would greatly appreciate if someone could explain me step by step 如果有人可以逐步解释我,我将不胜感激
Typically, one makes a matrix by wrapping a vector of values by row ( byrow=TRUE
) or the default, by column ( byrow=FALSE
) 通常,通过按行(
byrow=TRUE
)或默认值按列( byrow=FALSE
)包装值的向量来构成矩阵
matrix(
c(0.1,0.9,0,0,0,
0.1,0,0.9,0,0,
0,0.1,0,0.9,0,
0,0,0.1,0,0.9,
0,0,0,0.1,0.9),
nrow=5,ncol=5,
byrow=TRUE
)
Result: 结果:
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 0.9 0.0 0.0 0.0
[2,] 0.1 0.0 0.9 0.0 0.0
[3,] 0.0 0.1 0.0 0.9 0.0
[4,] 0.0 0.0 0.1 0.0 0.9
[5,] 0.0 0.0 0.0 0.1 0.9
Alternatively, and I'm not sure why you would need to do this, you could set up a loop where the index can be used to give the row and column indices: 另外,我不确定为什么需要这样做,您可以设置一个循环,在该循环中可以使用索引来提供行索引和列索引:
x <- c(0.1,0.9,0,0,0,
0.1,0,0.9,0,0,
0,0.1,0,0.9,0,
0,0,0.1,0,0.9,
0,0,0,0.1,0.9)
m <- matrix(NaN, 5, 5)
for(i in seq(length(m))){
ROW <- (i-1) %/% ncol(m) + 1
COL <- (i-1) %% ncol(m) + 1
m[ROW, COL] <- x[i]
}
m
Result: 结果:
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 0.9 0.0 0.0 0.0
[2,] 0.1 0.0 0.9 0.0 0.0
[3,] 0.0 0.1 0.0 0.9 0.0
[4,] 0.0 0.0 0.1 0.0 0.9
[5,] 0.0 0.0 0.0 0.1 0.9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.