2

I run into a very interesting problem. I wrote a function and wanted to check the output of some variables within the function as well as the return result.

observe({
    result <- myFunction()
})


myFunction <- function() {
    # some calculations
    # ...

    # create Dataframe from previous calculated variables
    # I was interested in the result of problematicVariable
    # thats why I wanted to make it global for checking, after
    # closing down the shiny app

    problematicVariable <<- data.frame(...)


    if(someCondition) {
        # ...        

    } else {
        # some calculations
        # ...
        # now I used problematicVariable for the first time

        foo <- data.frame(problematicVariable$bar, problematicVariable$foo)
    }

That gave me

data.frame: arguments imply differing number of rows: ...

However, since I made problematicVariable global I run the line where the App crashed manually (foo <- data.frame(problematicVariable$bar, problematicVariable$foo)). There was absolutely no problem. So I thought, that this is strange... I got rid of the double << and changed it to problematicVariable <- ... and now it works. So, using <<- to assign problematicVariable somehow made problematicVariable not available in the if...else.

Why causes <<- a behaviour like this? That messes with the scope?!

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • This is not C, properly define a function and its inputs and outputs. If the problem still occurs, provide a small, reproducible example. – Roman Luštrik Feb 25 '17 at 07:55

1 Answers1

3

<<- doesn't always create variables in the global environment. It will, however, create variables in the parent scope. Sometimes the parent scope is the same as the global environment.

?assign is what you want. But I don't see any reason to create global variables from inside a function. Just return the variable - code is easier to debug that way and you'll get fewer unexpected results.

EDIT: Suspected that this was a dupe. Good discussion about this can be found here.

Community
  • 1
  • 1
Oliver Frost
  • 827
  • 5
  • 18