Learn R Β· 10/15

Exploratory Data Analysis (EDA) & Basic Statistics

12 min read

Welcome, Data Detective! An R Guide to EDA πŸ•΅οΈβ€β™‚οΈ

Hey there! So, you've got a bunch of data. Maybe it's a spreadsheet, a database, or a text file. It feels like you've been handed a giant, messy box of clues for a mystery. Where do you even start? Trying to build a fancy machine learning model without looking at your data first is like trying to solve a crime without visiting the scene. You're gonna have a bad time.

This is where Exploratory Data Analysis (EDA) comes in.

Definition: EDA is the process of summarizing, visualizing, and getting to know your data. It's the detective work you do before the main investigation.

The Problem: Raw data is often overwhelming, messy, and full of hidden traps (like missing values or weird outliers). If you don't understand its basic characteristics, you can't trust any conclusions you draw from it.

The Solution: EDA provides a set of tools and a workflow to methodically uncover the story hidden in your data. It helps you spot patterns, identify anomalies, and form hypotheses. In this guide, we'll equip you with the fundamental tools in R to become a top-notch data detective.


1. Summary Statistics: Your Basic Detective Tools πŸ”Ž

Before you start looking for complex connections, you need to understand the basic facts. Summary statistics are your magnifying glass, helping you get a quick, high-level overview of your evidence.

Mean: The "Average Joe"

  • The Problem: You have a list of numbers (say, the daily sales of a coffee shop) and you want to find a single "typical" or "central" value.
  • The Concept: The mean is simply the arithmetic average. You add up all the values and divide by the count of values.
  • In R: We use the mean() function.
r
# A vector of daily coffee sales
daily_sales <- c(150, 200, 180, 220, 190, 300, 160)

# Calculate the average sales
average_sales <- mean(daily_sales)

print(average_sales)
# Output: [1] 200

A crucial argument for mean() is na.rm = TRUE, which tells R to ignore any missing values (NA) during calculation. Real-world data is messy and this is a lifesaver!

Median: The True Middle Ground

  • The Problem: What happens if on one day, a tech billionaire buys coffee for their entire company, and your sales jump to $5000? Your mean will be skewed and no longer "typical."
  • The Concept: The median is the middle value when you sort the data. If you have an even number of values, it's the average of the two middle ones. It's resistant to extreme outliers.
  • In R: We use the median() function.
r
# Our sales data, but with one crazy day
sales_with_outlier <- c(150, 200, 180, 220, 190, 5000, 160)

# The mean gets thrown off
mean(sales_with_outlier)
# Output: [1] 871.42

# The median tells a more realistic story
median(sales_with_outlier)
# Output: [1] 190

Funny Exaggeration: Calculating the mean income in a room of 10 regular people and one Jeff Bezos is a statistician's favorite joke. The mean would make everyone look like a multi-billionaire, while the median would give you a much more sensible picture.

Variance and Standard Deviation: The Spread-o-Meter

  • The Problem: Knowing the "center" isn't enough. Are all your data points tightly clustered around the mean, or are they spread all over the place?
  • The Concept: Variance measures the average squared difference of each value from the mean. A bigger number means more spread. The Standard Deviation is just the square root of the variance, which brings the measure back to the original units of the data, making it easier to interpret.
  • In R: We use var() for variance and sd() for standard deviation.
r
# Two sets of exam scores with the same mean
student_scores_A <- c(80, 82, 81, 79, 78) # Consistent students
student_scores_B <- c(100, 60, 80, 95, 65) # All over the place

mean(student_scores_A) # Output: 80
mean(student_scores_B) # Output: 80

# The standard deviation reveals the difference in consistency
sd(student_scores_A) # Output: [1] 1.58
sd(student_scores_B) # Output: [1] 17.01

A low standard deviation means the data points are reliable and close to the average. A high standard deviation means they are wildly unpredictable.

Quantiles and the summary() function: The Slicing Ninja

  • The Problem: How can we quickly understand the entire distribution of our data? We need to know the minimum, the maximum, and a few key points in between.
  • The Concept: Quantiles are cut-points that divide a dataset into equal-sized subgroups. You're already familiar with the median (the 50% quantile). The most common are quartiles, which divide the data into four equal parts:
    • Min: The absolute smallest value.
    • 1st Quartile (Q1): The value at the 25% mark.
    • Median (Q2): The value at the 50% mark.
    • 3rd Quartile (Q3): The value at the 75% mark.
    • Max: The absolute largest value.
  • In R: The quantile() function can give you any quantile you want. But for EDA, the industry-standard shortcut is the summary() function, which gives you all this and the mean for free!
r
# Using our original daily sales data
daily_sales <- c(150, 200, 180, 220, 190, 300, 160)

# The summary() function is your best friend
summary(daily_sales)
#   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
#  150.0   170.0   190.0   200.0   210.0   300.0

For a data frame, summary() cleverly applies itself to each column, giving you a lightning-fast overview of your entire dataset.


2. Understanding Relationships: Are These Clues Connected? πŸ”—

Okay, Detective. You've inspected each piece of evidence individually. Now it's time to see how they relate to each other. Do sales go up when the weather is warmer? Does a taller person tend to weigh more?

Covariance: The Directional Dude

  • The Problem: We want to know if two variables tend to move together. When one goes up, does the other also go up? Or does it go down?
  • The Concept: Covariance measures the joint variability of two variables.
    • Positive Covariance: When one variable is above its mean, the other tends to be above its mean (they move in the same direction).
    • Negative Covariance: When one variable is above its mean, the other tends to be below its mean (they move in opposite directions).
    • Zero Covariance: No linear relationship.
  • In R: We use the cov() function.
r
# Let's imagine data on ice cream sales and temperature
temperature <- c(20, 22, 25, 28, 30, 32)
ice_cream_sales <- c(100, 110, 130, 155, 170, 180)

cov(temperature, ice_cream_sales)
# Output: [1] 103.66

The positive value tells us they move together, but the number 103.66 is hard to interpret on its own. Is that a strong relationship or a weak one? It depends on the scale of our data. We need something better.

Correlation: The Standardized Superstar

  • The Problem: Covariance gives us the direction, but not the strength of the linear relationship in an easily comparable way.
  • The Concept: Correlation is just a standardized version of covariance. It always falls between -1 and +1, making it universally interpretable.
    • +1: Perfect positive linear relationship.
    • -1: Perfect negative linear relationship.
    • 0: No linear relationship.
    • Values like 0.8 or -0.7 indicate a strong relationship, while values like 0.2 or -0.1 indicate a weak one.
  • In R: We use the cor() function.
r
# Using the same data
temperature <- c(20, 22, 25, 28, 30, 32)
ice_cream_sales <- c(100, 110, 130, 155, 170, 180)

cor(temperature, ice_cream_sales)
# Output: [1] 0.993

A correlation of 0.993 is very close to 1, indicating a very strong positive linear relationship. As temperature goes up, ice cream sales go up in a very predictable way.

🚨 Interesting Fact & Critical Warning: Correlation does not imply causation! This is the most important rule in statistics. Ice cream sales are also highly correlated with shark attacks. Does eating ice cream cause sharks to attack? No! A hidden variable, summer heat, causes more people to buy ice cream AND more people to go swimming. Always be skeptical!


3. Basic Hypothesis Testing: Taking Your Suspect to Court βš–οΈ

You've found some patterns and relationships. But are they real, or could they have just happened by random chance? Hypothesis testing is how we use statistics to find out.

The Analogy: Think of it like a courtroom.

  • Null Hypothesis (Hβ‚€): The suspect is "innocent." This is the default assumption of no effect, no difference, or no relationship. (e.g., "There is no difference in test scores between the two groups.")
  • Alternative Hypothesis (H₁): The suspect is "guilty." This is what you, the data detective, are trying to prove. (e.g., "There is a difference in test scores.")
  • The p-value: This is the strength of your evidence. It's the probability of seeing your data (or something more extreme) if the null hypothesis were true. A small p-value (typically < 0.05) means your result is very unlikely to be due to chance, so you "reject the null hypothesis" and declare your finding statistically significant.

T-tests: The Two-Group Duel

  • The Problem: You have two groups and you want to know if their means are significantly different from each other. (e.g., Did the group using a new fertilizer grow taller plants than the control group?)
  • The Concept: A t-test compares the means of two groups and tells you the probability that they are the same.
  • In R: The t.test() function is incredibly useful.
r
# Let's test two different website button colors on user clicks
clicks_version_A <- c(10, 12, 11, 9, 13, 11, 10)
clicks_version_B <- c(14, 15, 13, 16, 15, 14, 13)

# Perform a two-sample t-test
t.test(clicks_version_A, clicks_version_B)

In the output, you'll look for p-value. If it's less than 0.05, you can confidently say there's a significant difference between the two versions.

ANOVA: The Big Group Battle Royale

  • The Problem: What if you have more than two groups? You can't just run a bunch of t-tests between all the pairs; it increases your chances of finding a false positive.
  • The Concept: ANalysis Of VAriance (ANOVA) is a statistical test used to determine if there are any significant differences between the means of three or more independent groups.
  • In R: We use the aov() function, which stands for "analysis of variance".
r
# Comparing the effectiveness of three different study methods on exam scores
# First, we need to structure our data in a data frame
scores <- c(78, 85, 82, 88, 75, 92, 95, 89, 91, 94, 65, 72, 68, 70, 75)
method <- rep(c("Method1", "Method2", "Method3"), each = 5)
study_data <- data.frame(scores, method)

# Fit the ANOVA model
# The formula `scores ~ method` means we want to see if `scores` depend on `method`
anova_result <- aov(scores ~ method, data = study_data)

# Look at the summary of the result
summary(anova_result)

The summary() output will give you a p-value (often shown as Pr(>F)). If it's less than 0.05, it tells you that at least one group is different from the others. It doesn't tell you which one, but it confirms that the "method" variable has a significant effect on scores.


4. Building a Complete EDA Workflow: The Full Investigation πŸ“‹

Now let's put it all together. A professional data analyst doesn't just run random commands; they follow a systematic workflow. We'll use one of R's famous built-in datasets, iris, which contains measurements for three species of iris flowers.

1. Load and Get a First Look (The Crime Scene Photos)
The very first step is to see what your data looks like.

r
# Load the iris dataset into your environment
data(iris)

# Print the first 6 rows
head(iris)

# Get the structure of the data: column names, data types, etc.
str(iris)

# Get a quick statistical summary of every column
summary(iris)

2. Clean the Data (Bagging and Tagging Evidence)
Real-world data often has missing values (NA). For this guide, we'll note that iris is a clean dataset. In a real project, you'd use functions like is.na() to find missing data and na.omit() to remove it or other methods to fill it in.

3. Univariate Analysis (Examining One Clue at a Time)
Now, we visualize individual variables.

  • Numeric Variables: Histograms are great for seeing the distribution.
  • Categorical Variables: Bar plots are perfect for seeing frequencies.
r
# Histogram of Sepal Length
hist(iris$Sepal.Length, main="Distribution of Sepal Length", xlab="Sepal Length")

# Bar plot of the different species
# We use table() to count the occurrences of each species first
counts <- table(iris$Species)
barplot(counts, main="Flower Species Count", xlab="Species")

4. Bivariate Analysis (Looking for Connections)
Now we look for relationships between pairs of variables.

  • Numeric vs. Numeric: Scatter plots are the best tool.
  • Numeric vs. Categorical: Boxplots show the distribution of a numeric variable for each category.
r
# Scatter plot of Petal.Length vs Petal.Width
plot(iris$Petal.Length, iris$Petal.Width, main="Petal Length vs. Width",
     xlab="Petal Length", ylab="Petal Width")

# Boxplot of Sepal.Length for each Species
boxplot(Sepal.Length ~ Species, data=iris, main="Sepal Length by Species",
        xlab="Species", ylab="Sepal Length")

5. Summarize Your Findings
After this process, a data detective would write a short report. For iris, we would conclude:

  • The dataset contains 150 observations of 3 species, with 50 of each.
  • Petal Length and Petal Width are very strongly positively correlated.
  • The 'setosa' species is clearly distinct from the other two, having smaller petals and sepals. 'Virginica' tends to have the largest measurements.

This structured approach turns a messy box of clues into a compelling story, setting the stage for any advanced analysis or modeling you want to do next. Happy investigating! πŸ•΅οΈβ€β™€οΈ


Further Reading & References πŸ“š

  • Official R Documentation: The ultimate source of truth for all R functions. The R Project for Statistical Computing
  • CRAN Task Views: Curated lists of packages for specific domains, like g-g-plot-2 for visualization. CRAN Task Views
  • "R for Data Science" by Hadley Wickham & Garrett Grolemund: An essential, freely available online book that is the industry standard for learning modern R. R for Data Science
  • Stack Overflow: For when you get stuck, the 'r' tag on Stack Overflow is an invaluable community resource. Stack Overflow - R Tag

Challenge

Challenge: Exploratory Data Analysis in R

You are a data analyst tasked with performing an initial exploratory data analysis (EDA) on a pre-loaded R data frame named store_data.

The store_data frame contains three columns:

  • daily_sales: A numeric vector representing sales figures, which may contain missing values (NA).
  • customer_traffic: A numeric vector representing the number of customers.
  • store_location: A factor with three levels: 'Urban', 'Suburban', and 'Rural'.

Your goal is to write a script that performs a complete EDA workflow. Write the R code to accomplish the following tasks in the specified order:

  1. Initial Inspection: Get a first look at the dataset. View the first few rows, examine the data types and structure of the columns, and generate a comprehensive statistical summary for the entire data frame.
  2. Univariate Analysis: Calculate the standard deviation of the daily_sales column. Ensure your calculation is not affected by potential missing values.
  3. Data Cleaning: Create a new data frame called cleaned_data that contains the store_data with all rows having one or more missing values removed.
  4. Bivariate Analysis: Using the cleaned_data frame, determine the linear relationship between daily_sales and customer_traffic by calculating their correlation coefficient.
  5. Hypothesis Testing: Using the cleaned_data frame, conduct a t-test to determine if there is a statistically significant difference in the mean daily_sales between the 'Urban' and 'Suburban' locations.
  6. Data Visualization: Using the cleaned_data frame, generate a boxplot to compare the distribution of daily_sales across all three store_location categories.

Expected result

Your script should contain the correct R functions to perform each step of the EDA workflow. The expected code includes:

  1. Three separate function calls for inspection: head(store_data), str(store_data), and summary(store_data).
  2. The sd() function applied to the daily_sales column with the argument to handle missing values: sd(store_data$daily_sales, na.rm = TRUE).
  3. The assignment of the result of na.omit() to a new variable: cleaned_data <- na.omit(store_data).
  4. The cor() function using the correct columns from the cleaned data frame: cor(cleaned_data$daily_sales, cleaned_data$customer_traffic).
  5. A t.test() using the formula interface to compare the two groups. A correct implementation would be: t.test(daily_sales ~ store_location, data = subset(cleaned_data, store_location %in% c('Urban', 'Suburban'))).
  6. A boxplot() call using the formula interface to visualize the relationship: boxplot(daily_sales ~ store_location, data = cleaned_data).
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.