[r] Function to clear the console in R and RStudio

I am wondering if there is a function to clear the console in R and, in particular, RStudio I am looking for a function that I can type into the console, and not a keyboard shortcut.

Someone has already provided such a function in this StackExchange post from 2010. Unfortunately, this depends on the RCom package and will not run on Mac OS X.

This question is related to r

The answer is


cat("\014")  

is the code to send CTRL+L to the console, and therefore will clear the screen.

Far better than just sending a whole lot of returns.


shell("cls") if on Windows,

shell("clear") if on Linux or Mac.

(shell() passes a command (or any string) to the host terminal.)


I developed an R package that will do this, borrowing from the suggestions above. The package is called called mise, as in "mise en place." You can install and run it using

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

Note that mise() also deletes all variables and functions and closes all figures by default. To just clear the console, use mise(vars = FALSE, figs = FALSE).


cat("\f") may be easier to remember than cat("\014").

It works fine for me on Windows 10.


cat("\014") . This will work. no worries


In Ubuntu-Gnome, simply pressing CTRL+L should clear the screen.

This also seems to also work well in Windows 10 and 7 and Mac OS X Sierra.


If you are using the default R console CTRL + L

RStudio - CTRL + L


Another option for RStudio is rstudioapi::sendToConsole("\014"). This will work even if output is diverted.

sink("out.txt")

cat("\014") # Console not cleared

rstudioapi::sendToConsole("\014") # Console cleared

sink()

In linux use system("clear") to clear the screen.


Here's a function:

clear <- function() cat(c("\033[2J","\033[0;0H"))

then you can simply call it, as you call any other R function, clear().

If you prefer to simply type clear (instead of having to type clear(), i.e. with the parentheses), then you can do

clear_fun <- function() cat(c("\033[2J","\033[0;0H"));
makeActiveBinding("clear", clear_fun, baseenv())

You may define the following function

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

which you can then call as clc().


You can combine the following two commands

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

If you are using the default R console, the key combination Option + Command + L will clear the console.