Programming with R: Commands You Can Rerun
Programming with R lets you turn a business calculation into a repeatable sequence of instructions. Instead of entering the same arithmetic whenever an assumption changes, you save commands, update the relevant inputs, and run them again. The essential skills are writing valid commands, understanding execution order, and checking that your saved instructions work without relying on earlier console activity.
Write commands with clear names
An R script is a text file containing R commands, usually saved with the extension .R. You can edit the script before executing it. The console, by comparison, accepts commands for immediate execution and displays output, messages, and errors.
Use assignment to store a value under an object name. The operator <- assigns the value of the expression on its right to the name on its left:
setup_fee <- 85
service_fee <- 240
total_fee <- setup_fee + service_fee
print(total_fee)Here, both fees are in Canadian dollars. R adds 85 and 240, stores 325 in total_fee, and displays that value through print().
Choose names that explain an object's purpose. service_fee is easier to interpret than x. R is case-sensitive: service_fee and Service_fee are different names. Spaces are not allowed within an ordinary object name, so underscores are useful separators.
A comment starts with # and continues to the end of that line. Use comments to explain assumptions or units:
setup_fee <- 85 # Canadian dollars; tax excludedCall functions deliberately
A function performs an operation. Write its name followed by parentheses containing its arguments, which are the inputs or settings supplied to it. For example, print(total_fee) asks print() to display the value stored in total_fee.
Some functions accept named arguments that make your intention clearer:
round(23.678, digits = 2)This returns 23.68. Here, digits = 2 specifies an argument inside the function call; it does not create a separate object named digits. You can request documentation with ?round or help("round") to check a function's purpose, arguments, and examples.
These commands serve different purposes:
Command | Purpose |
|---|---|
total_fee <- setup_fee + service_fee | Calculate a value and store it under a name. |
print(total_fee) | Explicitly display the stored value. |
help("round") | Open documentation for a function. |
Run commands in dependency order
R executes commands in the order you submit them. A calculation that uses an object needs that object to exist first. In the fee script, the two input assignments therefore belong before the calculation, and the calculation belongs before its output.
Assignment stores the result calculated at that moment. It does not establish a spreadsheet-style formula that automatically recalculates. If you change service_fee afterward, you must rerun the assignment to total_fee to update the stored total.
Save the complete script as a file such as fee_quote.R. If that file is in R's current working directory, execute its commands with:
source("fee_quote.R")Use print() for results you want displayed. With the default settings, source() does not automatically display every bare expression as the interactive console does.
When an error occurs, read its message and inspect the command that caused it. An “object not found” error often points to a spelling mismatch, a missing assignment, or commands executed out of order. Correct the cause, then rerun the complete script to check the result.
What to remember
- Use <- to store a calculated value under a clear, case-sensitive name.
- Write input assignments before commands that depend on them.
- Rerun dependent calculations after changing inputs.
- Use print() to display important results from a sourced script.
- Check that the saved script works in a fresh session.
Example: Programming with R for a Hire Quote
A small business hires a portable display stand. The supplier charges a one-time booking fee of 42 Canadian dollars and a daily fee of 18.50 Canadian dollars. Tax is excluded, and both rates remain fixed. You need a saved R script that calculates the quote and displays its total.
a) Write a complete script for a seven-day hire and calculate the displayed total.
Define the three inputs before using them in the calculation. The daily fee is in Canadian dollars per day, so multiplying it by the number of days gives the hire charge in Canadian dollars.
# Monetary amounts are Canadian dollars; tax excluded
booking_fee <- 42
daily_fee <- 18.50
hire_days <- 7
quote_total <- booking_fee + daily_fee * hire_days
print(quote_total)First calculate the daily charges:
Then add the one-time booking fee:
The command print(quote_total) displays 171.5, representing a total quote of 171.50 Canadian dollars. The booking fee is added once, while the daily fee is multiplied by the hire duration.
b) The customer extends the hire to nine days. Explain what happens if you run only hire_days <- 9, then revise the saved script so it reproduces the updated quote in a fresh session. Assume the file is saved as hire_quote.R in R's current working directory.
Running hire_days <- 9 changes the duration, but quote_total still contains 171.5 from the earlier calculation. Assignment does not keep an automatically updating formula. The calculation must execute again after the duration changes.
Update the original duration assignment in the saved file. The complete revised script is:
# Monetary amounts are Canadian dollars; tax excluded
booking_fee <- 42
daily_fee <- 18.50
hire_days <- 9
quote_total <- booking_fee + daily_fee * hire_days
print(quote_total)Execute the saved file with:
source("hire_quote.R")R assigns the inputs, calculates the new total, and explicitly prints it. The daily charges are:
Adding the booking fee gives:
The script displays 208.5, representing 208.50 Canadian dollars. As a check, two additional days cost ________ × 18.50 = ________ Canadian dollars, and 171.50 + 37.00 = 208.50 Canadian dollars. Every required input is defined in the saved file, so earlier session values are unnecessary.
An analyst is learning to navigate an interactive R session. Match each command to the information it displays when run successfully.
Opens documentation for the square-root function
Displays the folder used to resolve relative file paths
Lists object names in the current environment
Displays previously entered commands
history()
help("sqrt")
getwd()
ls()
A saved R script named invoice.R begins with:
amount <- 91.376 # Canadian dollarsYou run the file with source("invoice.R") using the default settings. Which command should you append to explicitly display the amount rounded to two digits after the decimal point?