mercredi 23 janvier 2019

Putting code chunk in an if statement changes assigning behavior R

I'm running into a very curious R issue. I have a chunk of code within an if statement that's assigning list elements, but that reacts differently whether it's run within the if statement (even if the if statement is if (1==1) {...}) or outside of it.

Basically, the code should just be doing if (true) {Raw[[1]]$params=params[[1]]; Raw[[2]]$params=params[[2]]; etc..}, but in the end, Raw[[1]]$params==Raw[[2]]$params and Raw[[3]]$params==Raw[[4]]$params, but only if it's in the if (true) {} statement. It works fine if it's not inside an if statement.

Let me show an example (this is a greatly simplified version of the original code; the motivation for the rep and the list assigning is for variable management reasons not relevant to the issue):

#----- Create variables
# params is a 4-element list
params0 <- list(runif(2),runif(4),runif(6),runif(8))
# Raw is a 2-element list, of which every element is another (named) list
Raw0 <- list(list(data=runif(3),params=runif(2)),
             list(data=runif(6),params=runif(6)))

dothing <- TRUE

#----- With if statement - does not correctly assign
Raw <- Raw0
params <- params0

if (dothing) {
  Raw <- rep(Raw,each=2)
  for (x in seq(1,length(params))) {
    Raw[[x]]$params <- params[[x]]
  }
}

# This should be false since params[[1]] ~= params[[2]], but returns true 
identical(Raw[[1]],Raw[[2]])

#----- Without if statement - does correctly assign
Raw <- Raw0
params <- params0

Raw <- rep(Raw,each=2)
for (x in seq(1,length(params))) {
  Raw[[x]]$params <- params[[x]]
}

# This returns false as expected
identical(Raw[[1]],Raw[[2]])

A final, very strange wrinkle in all this - in the original code, the assigning works fine if the code is run chunk-by-chunk (without missing any line), but does not correctly assign if the whole code is run at once.

Would anyone be able to tell me what I'm missing here? Thank you in advance for your help!

Aucun commentaire:

Enregistrer un commentaire