0

I am new to R language, and I am trying to avoid for loops in my program, so I use sapply() or ifelse(), but I meet some problems. Here is my program,

rowNum <- 1
  txn$'ACCT_NUM' <- sapply(c(1:nrow(txn)), function(x) if(txn$'ACCT_ID'[x]==MKAccts$'ACCT_ID'[rowNum]){
    return(MKAccts$'ACCT_NUM'[rowNum])
  }else{
    rowNum <- rowNum +1
    print(rowNum)
    return(MKAccts$'ACCT_NUM'[rowNum])
  })

and I found that every time in the sapply() function, when it calls the rowNum, it will be set back to 1 again, I think it might be caused by the reason that it is just be called, the change in the function in sapply() actually dose not reflect to the value out of the function, but is there anyway to realize this by using sapply() or ifelse()? Thank you!

Evelyn
  • 1
  • Please make a reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – emilliman5 Oct 06 '17 at 13:59
  • First, `rowNum` is not defined when you start. Furthermore, I am not sure that rowNum will persist as `sapply` progresses, i.e. `rowNum` will reset after each iteration. – emilliman5 Oct 06 '17 at 14:03
  • It has to do with variable scoping. The function creates a new environment every time it is called. Maybe you're looking for a `for` loop here. Take a look at: https://www.programiz.com/r-programming/environment-scope – manotheshark Oct 06 '17 at 14:05
  • 1
    `sapply` is just syntactical sugar - it writes a for loop with a little less typing and a little less flexibility. This case is more complicated than applying a simple function to each row, so it's a bad pace to use `sapply`. Just use a for loop. – Gregor Thomas Oct 06 '17 at 14:10

0 Answers0