I am currently working on a long data analysis script in RStudio and my console is getting extremely cluttered with previous outputs and error messages. Is there a built-in R function I can call within my script to refresh the view, or is there a specific keyboard shortcut for Windows and Mac that clears everything instantly without restarting the entire session?
3 answers
In RStudio, the most efficient way to clear the console is the keyboard shortcut Ctrl + L for both Windows and Mac. However, if you want to clear the console programmatically from within a script, R does not have a single "clear" function like other languages. You can simulate this by using cat("\014"), which sends a form-feed character to the console, effectively pushing the previous text out of view. In my experience, this is particularly useful at the beginning of a markdown-style script to ensure that the output you see during execution is fresh and not confused with old logs from a previous run.
Does using cat("\014") also clear the environment variables and the command history, or does it only hide the visible text in the console window?
If you want a custom command, you can define a function like cls <- function() cat("\014"). Then, simply typing cls() in the console will clear it anytime.
I agree with Barbara. Creating a custom cls() function is a great way to make R feel more like a standard terminal. It’s one of the first things I add to my .Rprofile so that it’s available every time I open RStudio for a new project. It definitely helps maintain a clean mental workspace during complex debugging.
Steven, that is a very important distinction to make. The cat("\014") function and the Ctrl + L shortcut only clear the visual display of the console. They do not touch your Global Environment or your history. If you want to wipe your variables as well, you would need to use rm(list = ls()). For a truly fresh start, I usually recommend using the "Restart R" option found in the Session menu of RStudio, which clears the memory and the console simultaneously, ensuring no "ghost variables" interfere with your new analysis.