The clear() function


Here was a common issue I had in grad school. I’d sit hunched before my computer, eyes twitching from looking at the screen too long, toilets flushing in the bathroom next door to my office. And to top it off, the AC’s broke, so I’m sweating like a swimming pool. And my R program JUST. WON’T. WORK!

Debug, debug, debug. My stomach growls, protesting another missed meal. My wife is texting, asking when I’m coming home. “As soon as I get this program working,” I say. “Kids are screaming, hurry up,” she says.

And I’m about to scream too. But then…the moment comes. I make a change and everything works. Wahoo!

Or is it wahoo?

The next day, I return to the same humid office to find that the program no longer works.

But-but-but-but…it worked yesterday!!!! How could it work yesterday, and not today? That lying sack of computer code!

The Problem

Let’s say you’ve got the following code

d = rnorm(100)
#### insert gobbledy goop that shouldn't change d###

#### and now we return to the bottom of the page###
### should be zero, eh? ####

But mean(d) says 1000! Say, what??? How could that be? Well, it seems you’ve forgotten one little thing. While going to a source file to edit a function (or something like that), you accidentally run this little line of code:

d = rnorm(100, mean=1000)

but forgot. So R originally assigned d a bunch of random numbers with a mean of zero, but later replaced it with a new set of random numbers with a mean of 1000. So, when you try to calculate the mean, it’s not going to remember what you originally assigned to it, but it’s going to remember the most recent assignment.

How often does it happen? Not often, but often enough that it’s a big hassle (especially if I’m sourcing functions and whatnot).

The Solution

To solve this problem, I used to include one line of code at the beginning of every R document


That clears R’s memory from the get-go, that way any debugging will be entirely contained within your current document. It’s a clear slate. A fresh start. Turning over a new leaf. Like January 1st or the end of an AA meeting–past sins forgotten, nuttin’ but clean programming ahead.

But…I got sick of typing all that in just to wipe R’s memory. So I built a function called clear(). The Gildroy Lockehart of programming, that function.

How to use it

The easiest way is to just wipe everything


Or you can remove only objects named dobby

clear("dobby", keep=F)

Or you can remove all objects but dobby (since, you know, dobby’s pretty much the man):

clear("dobby", keep=T)

Neato, eh?

Leave a Reply