How to Clear the Console in R

Gustavo du Mortier Feb 02, 2024
  1. Clear Console in R by Pushing the Output Up
  2. Combine Two Approaches to Clear Console in R
  3. Clear the R Console by Issuing a Shell Command
  4. Use a Pre-Developed Package to Clear Console in R
How to Clear the Console in R

You can clear the R console by typing a key combination that varies depending on each console implementation and the platform on which you run it. If you are running R Studio on Windows, for example, you can clear the screen by pressing CTRL+L or by running this code that sends the equivalent command to the console:

cat("\014")

But the above code may just send a line feed character instead of clearing the console in some cases. For example, if you are running other implementation of the R console, such as a DOS console, or if you are using a different operating system, such as Ubuntu or macOS.

Since there is no built-in function in R to clear the console natively, you need to pick one from the following options that best suits your needs.

Clear Console in R by Pushing the Output Up

A pretty commonplace option to clear the console from code is to push the output up until it disappears. You can do this by inserting a sufficient number of blank lines. In most cases, 50 lines should be enough, so you can add a function like the following:

clear_con <- function() cat(rep("\n", 50))

You can later call clear_con() whenever you need to clear the console.

Combine Two Approaches to Clear Console in R

Maybe one of the two previous techniques won’t work on some implementations of the R console. So, to make sure the console gets cleared on practically any situation, you can use the two approaches in combination.

cat("\014"); cat(rep("\n", 50))

This way, if the first command doesn’t clear the console, the second one definitely will.

Clear the R Console by Issuing a Shell Command

On some implementations of the R console, you can clear it from code by issuing a shell command to the operating system that empties the screen contents. The instruction you have to send depends on the operating system you are using. In case you use Windows, you can use the following command.

shell("cls")

In case you use Linux or Mac:

shell("clear")

Again, this option does not work on all operating systems and all versions of the R console.

Use a Pre-Developed Package to Clear Console in R

There is a package called mise that clears the console and, optionally, deletes all variables and functions. To install the package you can use these commands:

install.packages("mise")library(mise)

Once installed, you can use the mise function by executing this command.

mise()

By default, mise() will erase variables and functions. If you want it to clear the console, set False to the vars and figs parameters, like this.

mise(vars = FALSE, figs = FALSE)

You can find more info about the mise function on R Documentation.