Max Max - 3 days ago 6
R Question

Loop for matrix does not jump R

I guess this is a very easy question, however I don't understand why my loop does not jump:

I have a prefilled matrix:

0 1 2 3 ... 22
1 1/22 1/22 1/22 1/22 .. 1/22
2 1/22 1/22 1/22 1/22..
3 1/22
..
22 1/22.. .. 1/22


and now I want to have a matrix where the column name stands for the first number of rows where there is still a 1/22 in it and replace the rest with 1/25:

0 1 2 3 ... 22
1 1/22 1/22 1/22 1/22 .. 1/22
2 1/22 1/25 1/22 1/22..
3 1/22 1/25 1/25 1/22
..1/22 1/25 1/25 1/25
22 1/22.. .. 1/22


I wrote this code which should run onwards from column two, however it only fills out the first row?

for(i in 2:nrow(Matrix22)){
for(j in 2:ncol(Matrix22)){
Matrix22[i:22,j] <- 1/25
}
}

Answer

The solution by Tensibai is definitely better in this example, but to fix your original for loop solution you can also do the following

Matrix22<-matrix(rep(1/22,484),nrow=22,ncol=22)

for(j in 2:ncol(Matrix22)){
      Matrix22[j:nrow(Matrix22),j] <- 1/25
}

As you can see the nested for loops were not necessary as the column number determines the starting row where numbers need to be changed.

Comments