2

I have a file with an R program. I load it interactively on R and then I call the main function. During the execution I fill up some global lists but when I run the main function again I want those lists to be empty. How can I empty a filled up list? I tried doing

list <- NULL

after execution but it didn't work.

Atirag
  • 1,660
  • 7
  • 32
  • 60
  • Can you give some more context? Maybe the code for the entire function? When I run `list <- c("a", "b", "c")` and `list <- NULL` this seems to empty the list. – histelheim Sep 07 '13 at 19:33
  • 1
    Maybe you want `list <- list()` in order to add elements later via `list[[i]] <- ...`. (BTW, as you can see, the name is poorly chosen). – Ferdinand.kraft Sep 07 '13 at 19:43
  • 2
    It should be noted that relying on globals isn't best practice. If you explain what you're doing we can probably find a better way... – Dason Sep 07 '13 at 19:53
  • @Dason Yeah I know but I needed to do a quick program and I'm not really familiar with R so I used global variables for simplicity. I was programming a hanged man game so I needed global lists for the letters chosen by the player to compare them with the word chosen by the executioner. – Atirag Sep 07 '13 at 19:59
  • So is this an exercise to learn R? If so I would think that taking the extra time to learn how to do things 'the R way' would be more beneficial than just plowing through relying on bad practice. – Dason Sep 07 '13 at 20:03
  • Not really is for a friend who needs to do some experiments but knows nothing about programming. I can't spend too much on this though since I need to do stuff of my own that's why is kind of sloppy but functional... if I have time later I'll fix it. – Atirag Sep 07 '13 at 20:06

1 Answers1

6

Since you are setting them globally, you probably need list <<- NULL, because the <<- operator assigns global variables.

Edit, per @Dason's comment:

The <<- operator can in some circumstances fail to change the value of a variable in all possible environments. For that reason, it is better to use

assign("list", NULL, envir = .GlobalEnv)
Drew Steen
  • 16,045
  • 12
  • 62
  • 90
  • What does the <<- signify? – histelheim Sep 07 '13 at 19:47
  • 4
    As I explain in [this answer](http://stackoverflow.com/a/10904810/1003565) using `<<-` isn't quite as straightforward as you might expect. If you *absolutely* know you want it to be a global assignment then you're safer using `assign` – Dason Sep 07 '13 at 19:56
  • Can i do assign("list", NULL, envir = .GlobalEnv) then?? – Atirag Sep 07 '13 at 20:03
  • 2
    @Atirag: You could, but it is considered poor programming practice to create data objects that are named exactly as a class name. Preferred would be `assign("myList", NULL, envir = .GlobalEnv)` – IRTFM Sep 08 '13 at 15:38