Skip to Content
Course content

2: Working in the R Console and Scripts

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was helping a junior analyst who had spent an entire Tuesday afternoon "perfectly" cleaning a messy dataset. He was typing everything directly into the R console, tweaking parameters, and refining the logic until the final table looked exactly right. He was thrilled—until his laptop decided to force a system update and reboot. Since the console is ephemeral, every single line of that hard-won logic vanished. He had the result in his head, but no record of how he got there. He spent the next three hours trying to recreate the sequence of commands from memory.

This is the classic "Console Trap." In R, you have two primary ways to interact with the engine: the Console and the Script. Understanding when to use which is the difference between a professional workflow and a stressful one.

The Console as Your Interactive Sandbox

Think of the R Console—the area where you see the > prompt—as a conversation. You ask a question, and R answers immediately. It is fantastic for "quick and dirty" exploration. If you want to check the current working directory or quickly see the first few rows of a dataset you just loaded, the console is your best friend.

I use the console constantly to test a single function. For example, if I'm not sure if a specific regular expression will catch the dates in my data, I'll just type a quick test line like grep("2023", c("Jan 2023", "Feb 2024")) right into the prompt. I don't need to save that experiment; I just need the answer. But remember: the console is a scratchpad. Once you close the session, the commands are gone (unless you dig through the .Rhistory file, which is a headache you don't want).

Building a Reproducible Map with Scripts

When you move from "experimenting" to "building," you move into the Script editor. An R script (a file ending in .R) is simply a text file containing a sequence of R commands. Unlike the console, scripts are permanent. They are the "recipe" for your analysis.

The real power here is reproducibility. If you share a script with a colleague, they can run it and get the exact same result you did. In a professional environment, we almost never share the output of a console session; we share the script that produced it. Instead of typing mean(sales_data) into the console, you write it in your script, save the file as sales_analysis.R, and you now have a permanent asset that can be version-controlled with Git or audited by a manager.

The Workflow Loop

You won't actually choose one or the other; you'll use them in a loop. I typically keep my script open on the left and the console on the bottom. I write a few lines of logic in the script, then use Ctrl+Enter (or Cmd+Enter on Mac) to send those specific lines down to the console for execution.

This allows you to refine your code in the script editor—where you have the benefit of syntax highlighting and easy editing—while seeing the results instantly in the console. If a line throws an error, you don't re-type it in the console. You fix the line in the script and send it down again. This cycle is the heartbeat of R development. It keeps your logic clean and your results verifiable.




📋 Practical Task

Building a Reproducible Monthly Growth Calculator

Instead of running commands one-by-one, you will now create a permanent script to handle a simple calculation. This ensures that if you change your data later, you can rerun the whole process in one click.

Your Task:

  1. Open a new R Script file (File > New File > R Script).
  2. In the script editor, write the following code:
    # Monthly Revenue Data
    revenue <- c(12000, 15000, 14000, 19000)
    
    # Calculate the total revenue
    total_rev <- sum(revenue)
    
    # Calculate the average monthly revenue
    avg_rev <- mean(revenue)
    
    # Print the final results
    print(paste("Total Revenue:", total_rev))
    print(paste("Average Monthly Revenue:", avg_rev))
  3. Do not type this into the console. Instead, highlight all the code in your script window and press Ctrl+Enter (Windows/Linux) or Cmd+Enter (Mac).
  4. Verify that the results appear in the console.
  5. Save the file as revenue_calc.R.

Self-Check: If you close RStudio and reopen it, can you produce the same output by simply opening the script and running it again? If yes, you've successfully moved from ephemeral coding to reproducible scripting.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.