简体   繁体   中英

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.

My problem is: I need to create the matrix below using loop in 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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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