R Statistics and Machine Learning
Working with Data in R: From Raw Information to Insight
Programming is a way to describe a process so a computer can carry it out. In data analysis, that process may include importing information, cleaning it, calculating statistics, creating graphs, and saving results. Learning to program is valuable because data are now used across research, education, health, business, and many other fields. The goal is not merely to collect data, but to understand them and communicate what they reveal.
R is a programming language designed especially for statistical computing and data analysis. This lesson follows a typical analytical journey: understanding why programming helps, learning essential R concepts, preparing and visualizing data, analyzing patterns, and considering how machine learning can help with large datasets.
Why use programming for data analysis?
Statistical software with menus can be convenient for familiar, straightforward analyses. Programming adds several advantages, especially when an analysis involves many steps or needs to be repeated.
Reproducibility
A reproducible analysis records the steps used to produce a result. A script can show how the data were imported, cleaned, analyzed, and visualized. Another researcher can inspect those steps and run the script on the same data to check the result.
This matters in evidence-based practice and open science. A result is easier to evaluate when the process behind it is visible, rather than remembered or described only in general terms.
Automation
Menu-based software often requires repeated clicking when the same analysis must be run for several groups, datasets, or model settings. A program can automate those repeated steps. The same script can clean multiple files, run a sequence of analyses, and produce graphs without manually repeating every action.
Automation is especially useful when a method becomes complicated or when an analysis needs to be updated as new data arrive.
Communication and flexibility
A script communicates the analysis procedure in a precise form. Readers can see which variables were used, which transformations were applied, and how results were calculated. This can make it easier to review another researcher’s methods and to reproduce the analysis independently.
Programming also makes it possible to customize analyses and build functions that perform specialized tasks. R’s package system extends this flexibility: researchers can use functions created by others, including implementations of newer statistical and machine-learning methods.
Why R?
R is free and open source. Its large user community creates and shares packages, provides help, and develops new methods. R is designed with statistical work in mind and is available for major operating systems, including Windows, macOS, and Linux. A shared language and workflow can help researchers use consistent procedures across different computers.
R is a scripting language, so it is commonly used through a development environment rather than as a point-and-click application. RStudio is an integrated development environment, or IDE, that brings several useful tools into one interface:
- The text editor is used to write and save scripts.
- The console accepts R commands and displays their results.
- The workspace or environment shows objects currently stored in memory.
- The files, help, and plots panes help manage files, consult documentation, and view graphics.
The console is useful for quick calculations and testing commands. A saved script is better for preserving a complete analysis, because it records the commands in order.
A central advantage of programming is that the analysis becomes an explicit procedure: the same documented steps can be inspected, repeated, and adapted.
Think About It: Why might a saved script be more useful than a list of final results when another researcher wants to evaluate an analysis?
R’s basic building blocks
R works with objects. An object can store information, such as a number or table, or it can be a function that performs an operation on information. R is case-sensitive, meaning that uppercase and lowercase letters create different names: X and x are separate objects.
Calculations and logical comparisons
R can be used like a calculator. Its basic arithmetic operators include addition, subtraction, multiplication, division, and exponentiation. For example, 14 + 3 returns 17, while 3 ^ 3 returns 27.
R also evaluates logical statements. The equality operator == asks whether two values are equal; != asks whether they are unequal. The operators >, <, >=, and <= compare values. Logical operators such as &, |, and ! represent AND, OR, and NOT.
For example, the expression 50 == 50 + 1 evaluates to FALSE, because the two sides are not equal. These comparisons are useful for checking conditions, filtering data, and controlling what a function does.
R also provides functions for common mathematical operations. For example, log(36) calculates a logarithm, and sqrt(39204) calculates a square root. The name of a function is followed by parentheses containing the value or values to which it applies.
Assigning values and combining them
The assignment operator <- stores a value under a name:
my_height <- 177
This command creates an object called my_height. Assignment usually does not print the value as a calculation result, but the object becomes available for later commands.
The function c() combines values into a vector:
height_people <- c(177, 156, 189, 200)
The name c is commonly understood as “combine” or “concatenate.” Here, one object stores several height values. A later calculation can use the stored values instead of requiring them to be re-entered.
Think About It: What is the difference between entering a number directly into a calculation and assigning that number to a named object first?
Four important data structures
R uses different structures to organize information. Choosing a suitable structure makes data easier to analyze and interpret.
Vectors
A vector is a one-dimensional collection of values of the same basic type. A vector of names is a character vector; a vector of scores is numeric.
names <- c("Peter", "John", "Mary", "Kate")
IQ_scores <- c(100, 125, 143, 165)
The function class() reports an object’s class:
class(names)
class(IQ_scores)
The first object is character data, while the second is numeric data. A vector is useful when a set of values belongs together and has a consistent type.
Lists
A list can combine objects of different types or structures. For example, a list can hold both a character vector of names and a numeric vector of scores:
names_IQ <- list(names, IQ_scores)
The first list element contains the names, and the second contains the scores. Lists are useful when related information needs to be grouped together even though its components are not all the same type.
Matrices
A matrix is a two-dimensional structure arranged in rows and columns. Its entries are generally of the same basic type. Matrices are important in statistics because many methods, including regression and machine-learning procedures, use matrix-based calculations.
X <- matrix(IQ_scores, nrow = 4, ncol = 1)
This creates a matrix with four rows and one column. Its dimensions identify where values are located. As with other R objects, capitalization matters: the matrix named X is not the same object as x.
Data frames
A data frame is a table-like structure. Its columns are variables, and its rows are observations. Different columns can hold different types of information, which makes a data frame well suited to most ordinary datasets.
df <- data.frame(names, IQ_scores)
This creates a table in which each row pairs a name with a score. Data frames are central to many R workflows because they present observations and variables in a familiar tabular form.
Vectors store sequences of one type, lists group potentially different kinds of objects, matrices arrange values in two dimensions, and data frames organize observations into columns that may have different types.
Think About It: Which structure would best represent a dataset with one column of country names and another column of numeric populations, and why?
Functions: reusable instructions
A function takes input, performs instructions, and may return or display a result. Functions help avoid repeating the same instructions by hand. R includes many built-in functions, and packages add more. Users can also define their own functions.
A function definition has a name, optional arguments, and a body containing the instructions:
greeting <- function() {
print("Hello World!")
}
The function is named greeting. It has no arguments, so it requires no input. Calling it with greeting() runs the instructions inside its body. Text placed in quotation marks is a character string, not the name of an object.
A function that calculates BMI
A function can combine a calculation with additional logic. Body mass index is calculated using weight in kilograms and height in metres:
BMI=(height in metres)2weight in kilogramsA simple R function could be written as follows:
calculate_bmi <- function(weight, height) {
bmi <- weight / height^2
return(bmi)
}
The arguments weight and height are the function’s inputs. The function calculates BMI and returns it.
A function can also use conditional statements to provide a message based on the result. An if statement runs instructions when a condition is true. An else if statement checks another condition when the earlier condition was false, and else provides a final alternative. For example, a BMI function could calculate the value and then display a category or other message based on conditions. The calculation is still useful even if the function also provides an interpretation.
Arguments and optional behavior
A function’s arguments can control how it behaves. For instance, a function that summarizes a numeric vector might always print the mean and standard deviation, while an optional logical argument determines whether it also prints the median:
summarize_values <- function(x, print.median = FALSE) {
print(mean(x))
print(sd(x))
if (print.median) {
print(median(x))
}
}
The default value FALSE means that the median is not printed unless the caller requests it. To request it, the function can be called with print.median = TRUE. This illustrates how a single reusable function can support different needs.
Functions can also calculate multiple results. For example, a function with two numeric inputs could calculate and display both their sum and their product. Each instruction should be clearly separated in the function body so that R can recognize the sequence of operations.
Think About It: Why is a function with an optional argument more reusable than a function that always performs exactly the same set of actions?
The data-analysis workflow
Analysis is more than fitting a statistical model. A complete workflow transforms raw information into a result that can be interpreted and communicated. A useful sequence is:
- Import data into R.
- Tidy and transform the data into a useful structure.
- Visualize patterns and identify questions worth investigating.
- Model the data to quantify relationships or test hypotheses.
- Communicate the process and findings with clear tables, figures, and documentation.
These stages are not always strictly linear. A graph may reveal a problem with the data, requiring another cleaning step. A model may suggest a useful follow-up analysis. The workflow is often iterative: the analyst returns to earlier stages as new questions arise.
Packages and the tidyverse
An R package is a collection of functions and related tools. A package must generally be installed before it can be used, and then loaded into the current session.
install.packages("tidyverse")
library(tidyverse)
The install.packages() function obtains and installs a package. The library() function loads an installed package so that its functions can be used.
The tidyverse is a collection of packages that support common data-science tasks. Among its components are readr for importing data, dplyr for manipulating data, tidyr for tidying data, and ggplot2 for visualization. Using a collection of related packages can provide a connected workflow rather than requiring a separate tool for every step.
Importing and inspecting a dataset
A comma-separated values file, or CSV, stores table-like data as text with values separated by commas. The read_csv() function reads a CSV file into R:
gapminder <- read_csv("data.csv")
The object name gapminder is an example; the file path must refer to the actual file being read. Once imported, a dataset should be inspected before analysis. The following functions answer different basic questions:
View(gapminder)
dim(gapminder)
head(gapminder)
tail(gapminder)
names(gapminder)
View() opens a table-like view. dim() reports the number of rows and columns. head() displays the first six rows by default, while tail() displays the last six. names() returns the column names.
For example, a Gapminder-style dataset may contain columns for country, year, population, continent, life expectancy, and GDP per capita. Knowing the column names and dimensions helps establish what each row represents and what information is available for analysis.
Tidying, missing values, and filtering
A dataset may contain missing values, represented by NA in R. Missingness matters because many calculations cannot produce an ordinary result when a vector includes an NA.
For example, mean(age) may return NA if age contains a missing value. To calculate the mean using the available values, the function can be given the argument na.rm = TRUE:
mean(age, na.rm = TRUE)
Here, na.rm means “remove missing values.” Its default is FALSE, so missing values are not automatically ignored. Removing missing values can be appropriate for a calculation, but the analyst should still consider why the values are missing and whether excluding them affects interpretation.
Filtering creates a subset containing observations that satisfy a condition. The filter() function from dplyr can select observations from a particular year, continent, or population range:
gapminder_2007 <- filter(gapminder, year == 2007)
gapminder_asia <- filter(gapminder, continent == "Asia")
gapminder_mega <- filter(gapminder, pop > 10000000)
Each command creates a new data frame containing only rows that meet the stated condition. The new object name is chosen by the analyst. Filtering is useful when a research question concerns a specific period, group, or range of values.
Think About It: Why should missing values be examined before interpreting a mean calculated after removing them?
Visualizing data with ggplot2
Graphs help reveal patterns that may be difficult to notice in a table or a long written report. A visualization can make comparisons, distributions, and possible relationships easier to see. It is also a compact way to communicate findings.
ggplot2 creates graphs by building them in layers. The first layer identifies the dataset and maps variables to visual properties. Additional layers specify what marks to draw, such as points or bars.
Scatterplots
A scatterplot displays the relationship between two numeric variables. Each row of the dataset contributes a point. For example, GDP per capita can be mapped to the horizontal axis and life expectancy to the vertical axis:
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
geom_point()
The function ggplot() establishes the data and aesthetic mappings. The aes() function maps variables to visual attributes such as the horizontal position, vertical position, or color. The + operator adds another layer to the graph.
Point appearance can be adjusted. For example, alpha controls transparency and size controls point size:
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
geom_point(alpha = 0.5, size = 1)
Color can represent another variable, such as continent:
ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent)) +
geom_point()
This lets a reader compare the distribution of points across groups. A scatterplot may show an upward association between GDP per capita and life expectancy, but a visible association alone does not establish that one variable causes the other.
Boxplots
A boxplot compares the distributions of a numeric variable across categories:
ggplot(gapminder, aes(x = continent, y = lifeExp)) +
geom_boxplot()
A boxplot summarizes the distribution using the median, quartiles, and whiskers, while separately marking potential outliers. It does not display the mean as its central line by default. In a comparison of life expectancy by continent, differences in the positions and spread of the boxes can reveal group-level patterns.
Histograms
A histogram shows the distribution of a numeric variable by grouping values into intervals, or bins:
ggplot(gapminder, aes(x = lifeExp)) +
geom_histogram()
The horizontal axis represents life expectancy, and the bars show how many observations fall into each interval. A histogram can reveal where values are concentrated, how spread out they are, and whether a distribution has a long tail or multiple peaks.
A graph can provide an initial overview before a statistical model is chosen. For instance, a scatterplot can help identify broad trends, possible group clusters, and unusual observations. Visual patterns suggest questions for further analysis; they do not replace statistical reasoning.
Think About It: What can a scatterplot suggest about two variables, and what additional evidence would be needed before claiming that one causes the other?
Descriptive and inferential statistics
Before fitting a model, analysts often summarize the dataset. Descriptive statistics describe the observed data. Inferential statistics use data to estimate patterns or evaluate hypotheses beyond a simple description of the observations.
Summary statistics
The summary() function gives a quick summary of each variable:
summary(gapminder)
For numeric columns, the summary commonly includes minimum, lower quartile, median, mean, upper quartile, and maximum. For character columns, it reports information suited to character data rather than calculating numeric statistics.
Summaries can also be calculated separately for groups. For example, the by() function can apply summary() to portions of a dataset identified by continent:
by(gapminder, gapminder$continent, summary)
The $ operator selects a named column from a data frame. Thus, gapminder$continent refers to the continent variable inside the gapminder object.
Counting distinct values
The unique() function returns distinct values in a vector, while length() counts how many values are in a vector:
length(unique(gapminder$country))
This expression counts the distinct country names in the dataset. Counting unique values can be useful for checking how many categories or entities appear in a variable.
Correlation
Correlation measures the strength and direction of a linear association between two numeric variables. The cor() function calculates it:
cor(gapminder$lifeExp, gapminder$gdpPercap)
A correlation near zero indicates little linear association, while a positive correlation indicates that higher values of one variable tend to occur with higher values of the other. A negative correlation indicates that higher values of one tend to occur with lower values of the other. A correlation reported around 0.58, for example, indicates a positive association in the data, not proof that GDP per capita causes life expectancy to increase.
Comparing groups with a t-test
A t-test can assess whether the means of two groups differ more than would be expected from sampling variation under a specified null hypothesis. For example, a dataset can be filtered to compare life expectancy for Europe and Asia:
gapminder_subset <- filter(
gapminder,
continent %in% c("Europe", "Asia")
)
t.test(lifeExp ~ continent, data = gapminder_subset)
The formula indicates that life expectancy is compared across continent groups. The output includes a test statistic, a p-value, and a confidence interval for the difference in means. A negative test statistic can reflect the order in which the groups are compared; interpretation should be checked against the group means and the reported interval.
A paired t-test is appropriate when two measurements are meaningfully paired, such as measurements of the same units at two time points. In a comparison of years, observations need to be matched appropriately for the paired design to make sense. A factor can mark a numeric year variable as categorical, and paired = TRUE requests a paired comparison when the data are organized to support it:
t.test(value_2002, value_2007, paired = TRUE)
A t-test’s p-value helps assess evidence against the null hypothesis, but it does not by itself measure the size or practical importance of a difference.
Linear models
A linear model estimates how an outcome is associated with one or more explanatory variables. In R, lm() fits a linear model. For example:
mod <- lm(
lifeExp ~ pop + gdpPercap + year,
data = gapminder
)
summary(mod)
In the formula, lifeExp is the outcome, and pop, gdpPercap, and year are predictors. The model estimates the relationship between the outcome and each predictor while accounting for the other predictors included in the model.
The summary includes:
- Coefficients, which describe the model’s estimated relationships.
- Standard errors, test statistics, and p-values, which help assess uncertainty in the coefficient estimates.
- Residuals, which are differences between observed outcomes and model predictions.
- Adjusted R2, which summarizes the proportion of variation accounted for by the model while adjusting for the number of predictors.
An adjusted R2 of about 0.44, for example, indicates that the model accounts for roughly 44% of the observed variation under that measure. It does not mean that the model has explained every cause of life expectancy, nor does it establish causation. Coefficients must be interpreted in light of units, model assumptions, and the relationships among predictors.
R also allows specific parts of a model to be extracted. For example, mod$coefficients returns the estimated coefficients. Being able to access model components is useful when results need to be reformatted, compared, or used in subsequent calculations.
Think About It: Why is it important to distinguish a statistically detectable relationship from a causal explanation?
Communicating and preserving an analysis
Analysis is most useful when others can understand what was done and why. Clear organization and documentation support reproducibility.
Comments can be added to an R script with #. A comment describes the purpose of a line or section without being executed as an instruction:
# Fit a regression model predicting life expectancy
mod <- lm(lifeExp ~ pop + gdpPercap + year, data = gapminder)
Consistent naming and formatting also make scripts easier to read. A style guide can provide recommendations, although research groups may adopt their own conventions.
R Markdown combines written explanation with R code and its output in a document. It can be used to place methods, code, tables, and graphs together, making it easier to create a report in which results are connected to the steps that produced them.
A clear analysis therefore communicates both the findings and the path to those findings: which data were used, how they were prepared, what methods were applied, and what limitations remain.
Big data and machine learning
Some datasets contain very large numbers of observations, variables, or both. Examples include brain-imaging measurements, wearable-device records, genomic information, and social-network activity. Brain imaging can produce measurements for many spatial locations, called voxels. Wearable devices can record repeated health measures such as heart rate. Social platforms can generate large quantities of user activity data.
A useful distinction is the balance between the number of observations and the number of variables. In a traditional experiment, there may be many participants but relatively few measured variables. In some large or high-dimensional datasets, there may be many variables relative to the number of participants or cases. The number of observations is often denoted by N, while the number of variables or features is often denoted by P.
When the number of features is large, analysis can become difficult. Some methods seek to select a smaller set of useful features or otherwise manage the dimensionality of the data. Machine-learning methods can help build predictive models from such datasets, but they do not remove the need to understand how the data were collected or what the variables represent.
What machine learning does
Machine learning uses algorithms that learn patterns from data rather than relying only on a hand-written set of rules for every case. A model is developed from observed examples and then used to analyze or predict outcomes for new observations.
Three common machine-learning tasks are:
- Classification assigns an observation to a category. For example, a model might predict which of several known groups a new case resembles, based on its features.
- Regression predicts a numeric outcome. A model might use observed features to estimate an outcome for a new case.
- Clustering groups observations based on similarities in their features, without being given known group labels in advance. Clustering can help reveal hidden patterns or structure.
Classification and regression are commonly forms of supervised learning. The model learns from examples that include both input features and known outcomes. It then uses what it learned to predict outcomes for new observations.
Clustering is a form of unsupervised learning. The method receives input features but does not have known outcome labels to predict. Its purpose is to identify patterns or groupings within the data.
Inference and prediction
Statistical analysis and machine learning can both be used to study data, but they often emphasize different goals. Inference aims to formalize understanding of a data-generating process or evaluate hypotheses about how a system behaves. Prediction aims to forecast an unobserved outcome or future behavior.
Traditional statistical methods are often especially useful when the goal is to understand relationships or test a hypothesis. Machine learning is often especially useful when the goal is to predict accurately for new cases. These are emphases rather than absolute boundaries: both statistical and machine-learning methods can contribute to inference and prediction.
More data are not automatically better data
A large dataset is not necessarily a high-quality dataset. The meaning of its variables, the process that produced it, and possible biases all matter. An algorithm may detect patterns in the data even when those patterns are affected by an unusual data-collection process.
Google Flu Trends illustrates this risk. The system used flu-related search activity to estimate flu patterns and initially produced predictions that tracked official reports reasonably well. After the system attracted public attention, more people searched for flu-related information, including people who may not have had flu symptoms. Search behavior therefore changed in response to the prediction system’s publicity. The system then estimated flu activity that was higher than official reporting suggested.
This example shows how a measurement can stop representing the same thing when people’s behavior changes. Search counts may reflect illness, but they can also reflect curiosity, media attention, or awareness of the prediction itself. More observations of a changing or indirect signal do not necessarily improve the quality of the conclusion.
Big data and machine learning are therefore complements to, not replacements for, careful data collection and statistical reasoning. They can help generate new hypotheses, which can then be evaluated with further analysis or purpose-designed experiments. The legitimacy of the method and the quality of the data remain essential.
Think About It: How could a prediction system change the behavior it measures, and why would that make future predictions less reliable?
Comprehensive review
A reproducible R analysis begins with a clear sequence of steps. Data are imported, inspected, cleaned, transformed, visualized, modeled, and communicated. R objects organize information in forms such as vectors, lists, matrices, and data frames. Functions make operations reusable, while packages extend what R can do.
Data preparation is as important as modeling. Missing values need thoughtful handling, and filtering should match the research question. Visualizations help reveal distributions and relationships, while descriptive statistics, correlations, t-tests, and linear models answer different kinds of analytical questions. Their outputs require interpretation: association is not causation, statistical significance is not practical importance, and model fit does not explain every source of variation.
Machine learning extends analysis to tasks such as classification, regression, and clustering. Supervised methods learn from examples with known outcomes; unsupervised methods seek patterns without such labels. Large datasets can support discovery and prediction, but volume alone does not guarantee accuracy. Reliable conclusions depend on suitable methods, meaningful measurements, transparent procedures, and careful communication of what the data can and cannot show.

Ask anything
We've read this whole study set, so questions about it get the best answers.