Quinn
Quinn

Reputation: 439

incorrect output from for loop inside function

I've created a simple loop to calculate the efficiency of some simulated data. It performs perfectly well whilst as a loop:

NSE_cal <- NULL

for(i in 1:6) {
 Qobs <- flowSummary_NSE1[[i]][[3]]
 Qsim <- flowSummary_NSE1[[i]][[1]]
 object_cal <- NSEsums("NSE")
 NSE_cal <- c(NSE_cal, object_cal)
 }

#NSE_cal
#[1] 0.8466699 0.7577019 0.8128499 0.9163561 0.7868013 0.8462228

However, I want to apply this loop quite a few times - I need to vary the object flowSummary_NSE# and I have four different transformation types to apply. As a start, I put the loop inside a function, with only transformation needing to be specified, like so:

badFunction <- function(transformation){

 NSE_cal <- NULL

 for(i in 1:6) {
  Qobs <- flowSummary_NSE1[[i]][[3]]
  Qsim <- flowSummary_NSE1[[i]][[1]]
  object_cal <- NSEsums(transformation)
  NSE_cal <- c(NSE_cal, object_cal)
 }
  print(NSE_cal)
}

 badFunction("NSE")
 # [1] 0.8462228 0.8462228 0.8462228 0.8462228 0.8462228 0.8462228

The function has exactly the same information input as in the for loop on its own, except, for some reason, it outputs the same value for each case of i.

It is clear that I have done something wrong. But as far as I can see, it must be something simple contained to the function itself. However, incase it is an error elsewhere, I have attached the code that generates the necessary data and dependent functions (here)

Any help would be much appreciated

Upvotes: 1

Views: 200

Answers (1)

Frost_Maggot
Frost_Maggot

Reputation: 309

You need to pass objects into the nested function as arguments.

In your function_NSEsums.r script change the first line to NSEsums <- function(i, Qobs, Qsim) {

In your example_script.r change your code to the following:

badFunction <- function(transformation){

  NSE_cal <- NULL

  for(i in 1:6) {
    Qobs <- flowSummary_NSE1[[i]][[3]]
    Qsim <- flowSummary_NSE1[[i]][[1]]
    object_cal <- NSEsums(transformation, Qobs = Qobs, Qsim = Qsim)
    NSE_cal <- c(NSE_cal, object_cal)
  }

  print(NSE_cal)

}

badFunction("NSE")

[1] 0.8466699 0.7577019 0.8128499 0.9163561 0.7868013 0.8462228

Upvotes: 1

Related Questions