Basic R Command Reference

Best usage: copy/edit all R commands in a script file, run commands from the script.

The IDE RStudio provides a wonderful work arena for coding, including a script editor. However, I prefer to start students with the base R script editor. The editor presents a minimal interface: a console, a script window, and explicit command execution. That way we focus on R and not learning RStudio. The base R interface is also a part of the core installation from R. It exists across operating systems without additional dependencies.

To open the script editor

on macOS.

To open the script editor from the R.app

File > New Document

If successful, you’ll have two open windows like Fig 1.

on WinPC.

To open the script editor from RGui

File > New script.

RGUI.exe with open script editor.

Figure 1. RGUI.exe on Windows 11 with open script editor.

Hints about writing R code

  1. Use your local R installation with built-in script editor or Google CoLab as your R environment.
    • While other options are available, and highly recommended as you progress with coding, DrD will provide assistance with the former environments, not all possible R environments ;-).
  2. R is case sensitive.
    • Candy is treated by R as a different object than candy. That means, type commands exactly as provided.
    • For example candy<- will generate an error whilecandy <- will not — there was a missing space in the former instance.
    • Case sensitive coding is a common feature shared by most modern coding languages.
  3. Commands or object names may appear on web pages with single or double quotes. Do not include the quotes when typing or copying the commands or objects to your script file.
  4. All code printed in my eBooks has been verified, and every effort to maintain text-only entries of code on these pages has been made. Nevertheless, copying code from web pages may include formatting cues, which will cause errors when the code is run in R.
    • Common instances of problematic web formatting include smart quotes; R works only with straight quotes. Line breaks and em-dashes may also cause problems.
    • Copy/paste to and from your clipboard may be improved by using keyboard shortcuts Ctrl+Shift+V (Windows/Linux) or Cmd+Option+Shift+V (Mac) to paste as plain text.
    • Sometimes, the best remedy may be to retype rather than trying to identify hidden formatting marks included in the copy/paste routine from the web page.
  5. A hashtag # on a line of code instructs R that subsequent work is to be treated as comment and not as code for interpretation by R.
    1. Judicious use of commenting is considered coding best practice (eg, UK Government Analytical Community 2020).
  6. Troubleshooting? See DrD, your R code does not work for suggestions how to get help with coding challenges.

To run code in the script editor

To run R code from a script file use the following methods:

on macOS.

Select lines of code to highlight, then run, either from the context menu or via keyboard shortcuts: Command + Return/Enter.

on WinPC.

Select lines of code to highlight, then run, either from the context menu or via keyboard shortcuts: Ctrl+R.

Note 1. RStudio users. The default R script editor and RStudio are separate programs and both should run without issue. If, however, the R script editor fails to open, the likely cause is an older installation of RStudio. Solve by updating to new RStudio or removing RStudio.

1. Creating Objects and Basic Math

Task

R Code

What It Does

Assign a value

x <- 5

Stores 5 in object x

Create a vector

v <- c(1,2,3)

Creates a numeric vector

Addition

x + y

Adds values

Division

x / y

Divides values

Sum

sum(v)

Adds all elements

Mean

mean(v)

Calculates average

The arrow operator <- is called the assignment operator. On your keyboard use two separate keys sequentially: first the less-than key (<) then the hyphen or minus key (-). In R programming, the arrow operator is the preferred and conventional way to assign values to variables, while the equals sign (=) is primarily used to specify named arguments in function calls. This convention enhances code readability and helps avoid subtle bugs.

2. Importing Data

Task R Code Notes
Identify current working folder getwd() Helps confirm “Where you are” in your computer’s file structure.
Set working folder
setwd("/Users/Username/Desktop/BI104")   # macOS
setwd("C:/Users/Username/Desktop/BI104") # Windows
Assumes working folder BI104 is on Desktop.
Replace Username with your computer username.
Read CSV file
candy <- read.csv("candy.csv")
Reads comma-separated file from working directory.
Create data from text
candy2 <- read.table(
  header = TRUE,
  sep = ",",
  text = "
Color,MM_P,MM_C,Skit
Red,12,15,18
Blue,8,10,5
Green,10,12,14
Yellow,9,11,16
Orange,6,7,12
Brown,5,9,0"
)
header=TRUE uses first row as column names.
sep=”,” specifies comma separation.
Show datasets
candy
candy2
Prints the data frame.
Show structure
str(candy)
Displays rows, columns, and variable types.
Check working directory
getwd()
Shows where R looks for files.
Display part of an object
head(candy)
Shows first six rows of candy.
Attach data frame
attach(candy)
Allows column names to be used directly (use cautiously).

3. Accessing Data in a Data Frame

Task

R Code

What It Selects

Select column by name

candy$MM_P

Peanut column

Select multiple columns

candy[,2:4]

Columns 2–4

Column totals

colSums(candy[,2:4])

Sum of each brand

Create new object

total

<- sum(candy$MM_P)

Stores result

 

Note 2. use attach(candy) to avoid having to call the df candy$ then the variable name.

4. Making a bar chart

Bar chart

barplot(candy$MM_P,
       names.arg = candy$Color,
       xlab = "Color",
       ylab = "Count",
       main = "M&M Peanut Counts by Color")

Make a more visually appealing graph by adding colors to the bars. After names.arg insert new line

       col = candy$Color,

5. Plotting Scatterplot

Scatterplot

plot(candy$MM_P, candy$MM_C, 
     main="Title", 
     xlab="X label", 
     ylab="Y label")

Creates a scatterplot.

Add Labels to Points

text(candy$MM_P, candy$MM_C, 
     labels = candy$Color, pos = 3)

Adds color names near points.

6. Correlation

Task R Code Meaning
Compute correlation
cor(x, y)
Measures strength and direction of linear association.
Example
cor(candy$MM_P, candy$MM_C)
Correlation between MM_P and MM_C.

Interpretation:

  • Near +1 → strong positive relationship

  • Near 0 → weak/no linear relationship

  • Near –1 → strong negative relationship

7. Linear Models

Fit Model

model <- lm(MM_C ~ MM_P, data = candy)

Reads as: Predict Chocolate counts using Peanut counts.

View Model Summary

summary(model)

Provides:

  • Intercept

  • Slope

  • R-squared

  • p-values

Model Equation Form

General structure:

Y=β0​+β1​X

In this assignment:

Chocolate=Intercept+(Slope)×Peanut

8. Common Errors and Fixes

Problem or error message Likely Cause Fix
“object not found” Misspelled name Check capitalization
File not found Wrong directory
getwd()
First row becomes data Forgot

header=TRUE
Add argument
Plot looks wrong Reversed X and Y Check order in

plot()
Unexpected symbol or invalid input Smart quotes from Word, Google Docs, or web page Replace “ ” with standard quotes

" "

References and Suggested Readings

Grolemund, G. (2014). Hands-on programming with R. Bookdown version available at RStudio Education.

Lander J. (2017). R for Everyone: Advanced Analytics and Graphics, 2nd Edition. Addison-Wesley Data & Analytics Series, Addison-Wesley Professional, Boston, MA.

UK Government Analytical Community. (2020). Quality assurance of code for analysis and research (version 2025.2). Office for National Statistics, Analytical Standards and Pipelines hub: https://best-practice-and-impact.github.io/qa-of-code-guidance/

The folks at R-Project have made available a number of reference manuals:

  • An Introduction to R
  • The R language definition
  • The R Reference Index

/MD