Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205466

Trying to write an R function: is it the For Loop or the numeric vector that doesn't work?

$
0
0

I have a function like this (see below) and I genuinely cannot understand why it doesn't work.

The for loop itself, when run separately (not inside of a function) does work perfectly but the function always returns an empty vector, no matter the input value. I was doing the testing on c(3, 0, 4, 0, 99) as code, which should return me c(5, 0, 4, 0, 99). (The ones and twos work fine and have been tested in an earlier task).

run_code <- function(code, input) {

  opcode <- which(code %in% c(1, 2, 3, 4, 99))
  input <- input
  for (i in opcode) {                  
    if (code[i] == 1) {                                                   
      code[code[i+3]+1] <- code[code[i+1]+1] + code[code[i+2]+1]
    } else {
      if (code[i] == 2) {
        code[code[i+3]+1] <- code[code[i+1]+1] * code[code[i+2]+1]
      } else {                                                           
        if (code[i] == 3) {
          code[code[i+1]+1] <- input
        } else {
          if (code[i] == 4) {
            return(code[code[i+1]])
          } else {                                                      
            if (code[i] == 99) {
              break
            }
          }
        }
      }
    }
  }
  return(code)
}

Viewing all articles
Browse latest Browse all 205466

Trending Articles