简体   繁体   中英

Having trouble with nested loops (R)

I've wrote this nested loop so that, in the inner loop, the code runs through the first row; then, the outer one updates the loop so as to allow the inner one to run though the second row (and so on). The data comes from 'supergerador', a matrix. "rodadas" is the row size and "n" is the column size. "vec" is the vector of interest. Thank you in advance!

Edit: i, j were initially assigned i = 1, j = 2

for(e in 1:rodadas) {
  for(f in 1:(n-1)) {
    if(j >= 10) {
      vec[f] = min(supergerador[i, j] - supergerador[i, j - 1], 1 - supergerador[i, j])
    }
    else {
    vec[f] = func(i, j)
    }
    j = j + 1
  }
  i = i + 1
}

func is defined as

func = function(i, j) {
  minf = min(supergerador[i, j] - supergerador[i, j - 1], supergerador[i, j + 1] - supergerador[i, j])
  return(minf)
}

For reference, this is what the nested loop returns. You can tell that it only went through a single row.

> vec
[1] 0.127387378 0.068119707 0.043472981 0.043472981 0.027431603 0.027431603
[7] 0.015739046 0.008010766 0.008010766

I'm not quite sure what you are intending to do here, but here is a few suggestions and code edits:

Suggestions:

  1. If you have a for loop, use the loop-index for your subsetting (as much as plausible) and avoid additional indexes where plausible.
    • This avoids code clutter and unforseen errors when indices should be reset but aren't.
  2. Avoid double subsetting variables whenever possible. Eg if you have multiple calls to x[i, j] , store this in a variable and then use this variable in your result.
  3. Single line functions are fine, but should add readability to your code. Otherwise inlining your code is optimal from an efficiency perspective.

Incorporating these into your code I beliieve you are looking for

for(i in 1:rodadas) {
  for(j in 2:n) {
    x1 = supergerador[i, j]
    x2 = supergerador[i, j - 1]
    if(j >= 10) {
      vec[f] = min(x1 - x2, 1 - x1)
    }
    else {
      vec[f] = min(x1 - x2, supergerador[i, j + 1] - x1)
    }
  }
}

Here i am making the assumption that you wish to loop over columns for every row up to rodadas .

Once you get a bit more familiarized with R you should look into vectorization. With a bit more knowledge of your problem, we should be very easily able to vectorize your second for loop, removing your if statement and performing the calculation in 1 fast sweep. But until then this is a good place to start your programming experience and having a strong understanding of for-loops is vital in any language.

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