简体   繁体   中英

R nested for loop output

I don't receive correct results out of nested for loops in R (version 2.15.2).

GCP <- matrix(nrow=143,ncol=4)
for (i in 1:13) {
 for (j in 1:11) {
 GCP[i*j,1] = 410*(j-1)
 GCP[i*j,2] = 400*(i-1)
 # print(GCP[i*j,1])
 }
}

When I uncomment print(GCP[i*j,1]) I receive just what I expect:

[1] 0
[1] 410
[1] 820
[1] 1230
[1] 1640
[1] 2050
[1] 2460
[1] 2870
[1] 3280
[1] 3690
[1] 4100
[1] 0
[1] 410
[1] 820
[1] 1230
[1] 1640
[1] 2050
[1] 2460
[1] 2870
[1] 3280
[1] 3690
[1] 4100
[1] 0
...

But when I enter GCP[,1] after the loops have finished:

  [1]    0    0    0    0    0    0    0    0    0    0    0    0    0  410  820
 [16]  410   NA  410   NA  410  820  410   NA  410 1640  410  820 1230   NA  820
 [31]   NA 1230  820   NA 1640  820   NA   NA  820 1230   NA 2050   NA 1230 1640
 [46]   NA   NA 1230 2460 1640   NA 1230   NA 2050 1640 2460   NA   NA   NA 1640
 [61]   NA   NA 2460 2870 1640 2050   NA   NA   NA 2460   NA 2050   NA   NA   NA
 [76]   NA 2460 2050   NA 2870 3280   NA   NA 2460   NA   NA   NA 2870   NA 3280
 [91] 2460   NA   NA   NA   NA 2870   NA   NA 3280 3690   NA   NA   NA 2870   NA
[106]   NA   NA 3280   NA 3690   NA   NA   NA   NA   NA   NA 3280   NA   NA 3690
[121] 4100   NA   NA   NA   NA   NA   NA   NA   NA 3690   NA 4100   NA   NA   NA
[136]   NA   NA   NA   NA   NA   NA   NA 4100

How should I correct my code ?

The problem is that, when you do:

GCP <- matrix(nrow = 143, ncol = 4)

you are essentially initalising a matrix of dimensions (143,4) with NA . Then, you are constructing values only for row = i * j . And you are only printing those values. Maybe this code will help you clear things up a bit:

GCP <- matrix(nrow = 143, ncol = 4)
for (i in 1:13) {
    for (j in 1:11) {
        GCP[i*j,1] = 410*(j-1)
        GCP[i*j,2] = 400*(i-1)
        cat("i =", i, "j =", j, "i*j =", i*j, "GCP[i*j] = ", GCP[i*j,1], "\n")
    }
}

You'll see that the loop runs through all values of i and j . However, your indexes are only filling certain values = i*j . So, the remaining values are still NA . Since you are printing only those values that are already set, you never get NA when you print it.

I can't offer a solution unless you explain what you are trying to do. To start with, you are setting a matrix of ncol=4 but you are filling only the first two columns, and as @redmode points out, you ar rewriting some values.

Edit: Maybe then, this is what you're looking for?

GCP <- matrix(nrow = 143, ncol = 4)
for (i in 1:13) {
    for (j in 1:11) {
        GCP[11*(i-1) + j, 1] = 410*(j-1)
        GCP[11*(i-1) + j, 2] = 400*(i-1)
    }
}

This goes through the values from 1 to 143.

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