Clean Up Memory in R (Example) | Garbage Collection with gc() Function


In this article, you’ll learn how to collect garbage to clean up the memory in the R programming language.

The post will contain one example for the collection of data garbage to clean up memory space. To be more precise, the content of the page is structured like this:

Let’s just jump right in…


Creation of Example Data

Let’s assume that we have created the following three data objects in our R code:

A <- 1:1000                      # Create some data objects
B <- 1:9999
C <- 9999:1

After running the previous syntax you can find the data objects A, B, and C in your global environment of RStudio.

Now, let’s assume that our R code is getting slow, since those data objects are taking too much memory.

Then, we might to solve this problem by using the rm and list functions to clear our workspace:

rm(list = ls())                  # Clear workspace

After executing the previous R code, our workspace is empty.

Unfortunately, the memory might still be occupied, since the rm and list functions have only removed all data objects from the workspace, but they have not cleaned up the R memory.

So how can we resolve this problem?


Example: Clean Up R Memory Using gc() Function

This example shows how to clean up the R memory by using the gc function.

A call of the gc function causes a garbage collection to take place, and hence frees up some memory space.

To accomplish this, we simply have to run the following R syntax:

gc(reset = TRUE)                 # Garbage collection

After running the previous R code, the R memory should be cleaned up.

In addition, the gc function can be used for the report on memory usage. Hence, the gc function also returns the following report to the RStudio console:


table 1 matrix clean up memory gc function


Video, Further Resources & Summary

Would you like to learn more about the collection of data garbage to clean up memory space? Then you could have a look at the following video on my YouTube channel. I show the R programming codes of this tutorial in the video:



Furthermore, you may want to read the related R programming tutorials on


Summary: In this R tutorial you have learned how to remove garbage to clean up memory space. If you have any additional questions, please let me know in the comments.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

2 Comments. Leave new

  • To actually remove “garbage collection” in the R Workspace, it is important to set the “reset” argument in the gc() function to TRUE (because the default “= FALSE”):

    gc(reset = TRUE)


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.