R is a programming language used for data analysis, statistics, graphing, and scientific computing. This cheat sheet helps students remember the most common commands and patterns used in beginner R programs. It is useful when writing scripts, cleaning data, making plots, or checking calculations.
The focus is on quick syntax reminders rather than long explanations.
Key Facts
- Assign a value to a variable with x <- 10, and print it by typing x or using print(x).
- Create a vector with c(), such as scores <- c(82, 91, 77, 88).
- Access vector items with square brackets, where scores[1] returns the first item because R uses 1-based indexing.
- Create a data frame with data.frame(name = c("Ana", "Ben"), score = c(90, 85)).
- Select a data frame column with df$score or df[ , "score"].
- Define a function with add <- function(a, b) { return(a + b) }.
- Calculate common summaries with mean(x), median(x), sum(x), min(x), max(x), and sd(x).
- Make basic plots with plot(x, y), hist(x), boxplot(x), and barplot(values).
Vocabulary
- Variable
- A named storage location that holds a value, such as x <- 5.
- Vector
- An ordered collection of values of the same basic type, created with c().
- Data frame
- A table-like structure in R with rows and columns, often used to store datasets.
- Function
- A reusable block of code that takes input values, performs steps, and often returns an output.
- Index
- A position number used to access an item in a vector, list, or data frame.
- Package
- A collection of extra R functions and data that can be installed and loaded when needed.
Common Mistakes to Avoid
- Using = when the class expects <- for assignment can make code harder to read or inconsistent with R style, even though = sometimes works.
- Forgetting that R starts indexing at 1 is wrong because x[0] does not return the first item in a vector.
- Mixing text and numbers in one vector changes the data type, so c(1, 2, "3") stores values as text rather than pure numbers.
- Writing a column name without the data frame name can fail because R may not know which table the column belongs to.
- Forgetting parentheses in a function call is wrong because mean is the function object, while mean(x) actually runs the calculation.
Practice Questions
- 1 Create a vector named temps with the values 68, 72, 75, 71, and 69, then write the R command to find its mean.
- 2 Given scores <- c(84, 91, 78, 88), what value is returned by scores[2]?
- 3 Write an R command that creates a data frame named students with columns name = c("Mia", "Leo") and grade = c(95, 89).
- 4 Why is a data frame usually better than separate vectors for storing a class roster with names, ages, and test scores?