Below is a cheat sheet crafted to help reinforce the core R concepts and functions you’re likely encountering in Google’s Coursera Data Analytics course. This guide covers basic R syntax, common functions, data structures, and some data manipulation functions (including a few from the dplyr package) that you’ll often use while cleaning, analyzing, and visualizing data. You can keep this cheat sheet handy as you work through assignments and projects.
1. Basic R Syntax & Environment
-
Assignment Operator
Use <- (or = in many cases) to assign values to variables.
x <- 10
y = 5
-
Comments
Use # to add comments.
# This is a comment
-
Help & Documentation
Use ?function_name or help(function_name) to get help on a function.
?mean
help(mean)
2. Data Structures in R
-
Vectors
A one-dimensional array that holds elements of the same type.
nums <- c(1, 2, 3, 4, 5)
chars <- c("a", "b", "c")
-
Matrices
Two-dimensional data structure with rows and columns.
m <- matrix(1:12, nrow = 3, ncol = 4)
-
Lists
Can hold elements of different types.
my_list <- list(number = 42, text = "hello", vector = c(1,2,3))
-
Data Frames
Tabular data; columns can be of different types.
df <- data.frame(
id = 1:3,
name = c("Alice", "Bob", "Charlie"),
score = c(90, 85, 95)
)
-
Factors
Used for categorical variables.
gender <- factor(c("male", "female", "female", "male"))
3. Basic Data Input/Output
-
Read CSV Files
Use read.csv (or readr::read_csv for a faster version if you have the package).
my_data <- read.csv("path/to/your/file.csv", stringsAsFactors = FALSE)
-
Write CSV Files
Save data frames to a CSV file.
write.csv(my_data, "path/to/save/output.csv", row.names = FALSE)
-
View Data
head(df) # first 6 rows of a data frame
tail(df) # last 6 rows
str(df) # structure of an object, useful for checking data types
summary(df) # statistical summary of each column
4. Basic Operations & Functions
-
Arithmetic & Logical Operations
# Arithmetic
sum_val <- 5 + 3 # Addition
diff_val <- 10 - 2 # Subtraction
prod_val <- 4 * 3 # Multiplication
quot_val <- 20 / 4 # Division
power_val <- 2^3 # Exponentiation
# Logical
result <- (5 > 3) # TRUE
equal <- (5 == 5) # TRUE
notequal <- (5 != 3) # TRUE
-
Common Functions for Summaries
mean_val <- mean(nums) # Calculate the mean
median_val <- median(nums)
sum_val <- sum(nums)
sd_val <- sd(nums) # Standard deviation
length(nums) # Number of elements in a vector
-
Creating User-Defined Functions
add_numbers <- function(a, b) {
return(a + b)
}
result <- add_numbers(10, 5) # returns 15
5. Data Manipulation Techniques
Base R Subsetting & Indexing
-
Indexing Vectors & Data Frames
# Vector indexing
nums[1] # First element
nums[c(1, 3)] # 1st and 3rd elements
# Data frame indexing
df[1, ] # First row
df[, "name"] # The column "name"
df[1:2, c("id", "score")] # Subset of rows and selected columns
-
Logical Subsetting
df[df$score > 90, ] # Rows with score greater than 90
Using dplyr for Data Manipulation
Make sure to install and load the package if you haven’t already:
install.packages("dplyr") # if not already installed
library(dplyr)
-
filter()
Select rows that meet a condition.
df_filtered <- filter(df, score > 90)
-
select()
Choose specific columns.
df_selected <- select(df, id, score)
-
mutate()
Add new columns or modify existing ones.
df <- mutate(df, adjusted_score = score * 1.1)
-
arrange()
Reorder rows.
df_sorted <- arrange(df, desc(score))
-
group_by() and summarise()
Transform data by groups and summarize.
df_summary <- df %>%
group_by(name) %>%
summarise(mean_score = mean(score, na.rm = TRUE))
-
Piping with %>%
Chain commands together.
df %>%
filter(score > 80) %>%
select(id, score) %>%
arrange(score)
6. Data Visualization
-
Base R Plotting
A quick plot to get started.
plot(df$score, main = "Scores Plot", xlab = "Index", ylab = "Score")
hist(df$score, main = "Histogram of Scores", xlab = "Score")
-
Using ggplot2
For more advanced graphics, you might use ggplot2 (if your course covers it).
install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(x = score)) +
geom_histogram(binwidth = 5, fill = "blue", color = "black") +
labs(title = "Histogram of Scores", x = "Score", y = "Frequency")
7. Additional Tips
-
Missing Values
Check and handle missing values using is.na() and functions like na.omit().
any(is.na(df))
df_clean <- na.omit(df) # Removes rows with any missing value
-
Type Conversion
Convert data types using functions like as.numeric(), as.character(), as.factor(), etc.
df$score <- as.numeric(df$score)
df$name <- as.factor(df$name)
-
Saving Your Workspace
Save your objects if you need to pick up where you left off.
save.image("my_workspace.RData")
load("my_workspace.RData")
8. Common Troubleshooting and Best Practices
-
Read Error Messages Carefully:
They often indicate what’s wrong (e.g., type mismatches or incorrect indexing).
-
Check Data Structure Regularly:
Using str() and summary() can save time by revealing data type issues early.
-
Avoid Overwriting Base Functions:
Use descriptive variable names to avoid conflicts with R’s built-in functions.
-
Comment Your Code:
This makes it easier to follow your logic, especially when using pipes and multiple transformations.
-
Practice Incrementally:
Test small blocks of code before building longer scripts so that debugging is simpler.
This cheat sheet focuses on functions and syntax you’re likely to use as you progress in data analytics with R, from basic operations and data import/export to data manipulation and visualization. Feel free to add notes or expand it as you encounter new functions and use-cases during your course. Happy coding and good luck with your penultimate section!