Reputation: 7198
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.
Upvotes: 372
Views: 598354
Reputation: 8523
I know this question is very old, but I found myself visiting it many times looking for a totally different answer:
n = 20
for (i in 0:n) {
cat(100*i/n, "% \r")
flush.console()
Sys.sleep(0.01) #do something slow
}
flush.console()
will kind of "clear the console in r and studio", maybe not in OP's terms but still.
This code will act like a progress bar in the console. For each iteration, the percentage is incremented and then erased on the next iteration.
Note that this won't work without \r
or with an \n
, for some reason.
Upvotes: 1
Reputation: 9107
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()
Upvotes: 1
Reputation: 559
shell("cls")
if on Windows,
shell("clear")
if on Linux or Mac.
(shell()
passes a command (or any string) to the host terminal.)
Upvotes: 39
Reputation: 438
cat("\f")
may be easier to remember than cat("\014")
.
It works fine for me on Windows 10.
Upvotes: 32
Reputation: 141450
You can combine the following two commands
cat("\014");
cat(rep("\n", 50))
Upvotes: 4
Reputation: 1876
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())
Upvotes: 18
Reputation: 21532
You may define the following function
clc <- function() cat(rep("\n", 50))
which you can then call as clc()
.
Upvotes: 37
Reputation: 1207
If you are using the default R console, the key combination Option + Command + L will clear the console.
Upvotes: 109
Reputation: 61505
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.
Upvotes: 27
Reputation: 6344
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.
Upvotes: 628
Reputation: 171
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)
.
Upvotes: 17