1. Home
  2. Explore
  3. Statistics
  4. R Statistics and Machine Learning

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

R Statistics and Machine Learning

R, Statistics, Data Analysis, and Machine Learning

Why programming and R matter

Data analysis involves more than running a statistical test. A complete analysis may require collecting or importing data, cleaning and reshaping it, exploring it, fitting a model, and communicating the results. Programming can bring these steps together in a consistent workflow.

The ability to understand, process, interpret, visualize, and communicate data is increasingly valuable across professional, academic, and educational settings. Programming helps analysts move from raw data to useful evidence in a way that can be checked and repeated.

Benefits of programming for research

  • Reproducibility: An analysis script records the steps used to process data and produce results. Another researcher can inspect the script, rerun the analysis, and see how the results were obtained.

  • Automation: Repetitive work—such as applying the same analysis to several groups or repeatedly generating plots—can be performed by code rather than by repeating manual actions.

  • Transparency and communication: A script makes analytical decisions visible. Readers can see which data were selected, which transformations were applied, and which models were fitted.

  • Flexibility: Code can be adapted to new datasets, complex analyses, and specific research questions.

  • Integration of the workflow: Data preparation, statistical analysis, visualization, and reporting can all be handled in a connected process rather than scattered across spreadsheets and separate software.

Menu-based statistical software can be convenient for straightforward analyses. However, repeated clicking becomes cumbersome when an analysis is complex, must be repeated for multiple subgroups, or needs to be updated. A script makes such workflows easier to repeat and audit.

Why use R?

R is a programming language designed especially for statistical analysis and data work. It is useful because it is:

  • Free and open source: It can be used without purchasing a software license, and developers can contribute to its development.

  • Supported by a large community: Users can find guidance, examples, and solutions to common problems online.

  • Extensible: Packages add tools for statistical methods, machine learning, visualization, data manipulation, and other tasks. Researchers can also write their own functions and algorithms.

  • Script-based: Scripts support reproducibility, automation, and transparent reporting.

  • Available across operating systems: R can be used on Windows, macOS, and Linux, helping researchers work in compatible environments.

  • Useful for current methods: Community-developed packages can make newer methods available, including methods that may not be included in traditional statistical software.

R is not the only useful programming language. Python and other languages are also widely used in data science. R is particularly well suited to statistical work and research analysis.


R and RStudio

R and the development environment

R is the programming language that runs commands and performs computations. RStudio is an integrated development environment (IDE): an application that provides a convenient interface for writing, running, and organizing R code. R itself can be used through a command-line interface, while RStudio brings common tools together in one workspace.

A typical RStudio interface includes:

  • Source editor: A place to write and save scripts. Text in the editor does not run until it is sent to R.

  • Console: The command line where R executes code and displays results.

  • Environment or workspace pane: Shows objects—such as variables and datasets—currently stored in memory.

  • Files, plots, packages, and help panes: Provide access to files, visualizations, package management, and documentation.

Using a script editor is especially helpful for longer commands and analyses. Code can be saved, revised, and rerun instead of being entered only in the console.


R fundamentals

Arithmetic and logical expressions

R can perform basic arithmetic directly in the console:

14 + 3
10 / 12
3 * 18
3 ^ 3

It also provides functions for common mathematical operations:

log(36)
sqrt(39204)

Logical expressions compare values and return TRUE or FALSE. For example:

50 == 50 + 1
50 != 50 + 1

Common comparison operators include:

  • == tests whether two values are equal.

  • != tests whether they are unequal.

  • > and < test whether one value is greater or less.

  • >= and <= test greater-than-or-equal and less-than-or-equal.

Logical values can also be combined using AND, OR, and NOT operations. These comparisons are useful for checking conditions and selecting data.

Objects, data, and assignment

R is an object-oriented language. Data and functions are both objects:

  • Data objects store information.

  • Functions operate on data and return results or perform actions.

An assignment stores a value under a name:

my_height <- 177

The assignment operator is <-. Assignment generally does not print the value automatically. The value can be displayed by entering the object’s name:

my_height

R is case-sensitive. For instance, X and x are different object names. Consistent capitalization is essential when creating and using objects.

The function c() combines values into a vector:

heights <- c(177, 156, 189, 200)

A vector can contain multiple values under one object name. R’s output and environment pane can help identify the stored object and its type.

Data classes

R uses different structures for storing data. Four important structures are vectors, lists, matrices, and data frames.

Vectors

A vector is a one-dimensional collection of values of a common data type. For example, a character vector can store names:

names <- c("Peter", "John", "Mary", "Kate")

A numeric vector can store scores:

IQ_scores <- c(100, 125, 143, 165)

The class() function checks an object’s class:

class(names)
class(IQ_scores)

These examples return character and numeric classes, respectively.

Lists

A list can combine objects of different types or structures. For example, a list can contain both a character vector of names and a numeric vector of scores:

names_IQ <- list(names, IQ_scores)

The list can be inspected by entering its name. Its components are stored separately within the list.

Matrices

A matrix is a rectangular, two-dimensional structure organized by rows and columns. Matrix elements share a common data type. Matrices are important in statistics because many models and computations use matrix operations.

X <- matrix(IQ_scores, nrow = 4, ncol = 1)
class(X)

The arguments specify the number of rows and columns. Because R is case-sensitive, X and x are distinct names.

Data frames

A data frame is a table-like structure. Its columns can contain different data types, while values within each column generally share a type. This makes data frames useful for datasets that contain several variables, such as names and numeric measurements.

df <- data.frame(names, IQ_scores)

Printing df displays the values as rows and columns. In a data frame, each row typically represents an observation and each column a variable.

Functions

A function is a reusable set of instructions. A function can receive input values, perform operations, and return or display an outcome.

Functions may be:

  • Provided by R or packages: These are written by other developers and become available when the relevant package is loaded.

  • User-defined: These are written by the analyst for a particular task.

A function definition has a name, optional arguments, and a body containing the instructions:

greeting <- function() {
  print("Hello World!")
}

The function is run by calling its name with parentheses:

greeting()

Text surrounded by quotation marks is a character string, not an object name.

Writing a BMI function

Body mass index (BMI) is calculated from weight and height:

BMI=weight in kilograms(height in meters)2\text{BMI} = \frac{\text{weight in kilograms}}{(\text{height in meters})^2}BMI=(height in meters)2weight in kilograms​

A simple R function can calculate it:

BMI <- function(height, weight) {
  weight / height^2
}

The height must be supplied in meters, not centimeters. A more elaborate function can also use conditional statements to display a message based on the calculated value. This shows that functions can do more than return a number: they can apply decision rules and communicate interpretations.

Conditional statements

An if statement runs instructions when a condition is true. An else if statement checks another condition when the previous one is false, and else handles the remaining cases. Conditional logic allows a function to respond differently to different inputs.

For example, a function could calculate BMI, check which range it falls into, and display an appropriate message. Any interpretation should be based on clearly specified criteria rather than on the calculation alone.

Functions with optional behavior

A function can accept a logical argument that controls whether an optional output is produced. For example, a function that summarizes a numeric vector might always print the mean and standard deviation, while printing the median only when an argument such as print.median is set to TRUE.

Default arguments allow a function to have a behavior when the user does not specify a value:

result2 <- function(x, print.median = FALSE) {
  print(mean(x))
  print(sd(x))

  if (print.median) {
    print(median(x))
  }
}

In this example, the median is omitted by default and included when the function is called with print.median = TRUE.

Code structure and line breaks

Curly braces {} mark the beginning and end of a function body or other code block. Placing instructions on separate lines makes the structure easier to read and helps prevent errors. For example, calculations and print statements should be clearly separated into individual instructions.


A data-analysis workflow

A data-analysis workflow describes how raw data are turned into interpretable findings and communicated results. The process is iterative: exploration and modeling may reveal a need to revise the data preparation or ask a new question.

Main stages

  1. Import: Read data into the analysis environment.

  2. Tidy and transform: Clean the data and reshape or select information into a form suited to analysis.

  3. Visualize: Plot the data to identify distributions, patterns, and possible relationships.

  4. Model: Apply statistical or machine-learning methods to examine relationships or make predictions.

  5. Evaluate and refine: Inspect the results and decide whether additional analyses or changes are needed.

  6. Communicate: Present findings in a clear form, such as figures, tables, and written explanations.

Analysts sometimes focus mainly on the modeling stage, but import, cleaning, transformation, visualization, and communication are also central parts of sound analysis.

The tidyverse package collection

The tidyverse is a collection of R packages for common data-science tasks. Instead of installing each package separately, users can install the collection and load it when needed:

install.packages("tidyverse")
library(tidyverse)

Installing a package makes it available on the computer. Loading it makes its functions available in the current R session.

Important tidyverse packages include:

  • readr: Imports data, including comma-separated-value files.

  • dplyr: Selects, filters, and transforms data.

  • tidyr: Helps clean and reshape data.

  • ggplot2: Creates visualizations.

  • tibble: Provides a modern form of table-like data structure.

  • purrr: Supports work with functions and collections of data.

The collection supports several stages of a data-analysis workflow, not just statistical modeling.


Importing and inspecting data

A common dataset used for examples records country-level information across years, including population, continent, life expectancy, and GDP per capita.

Reading a CSV file

The read_csv() function from readr imports a CSV file:

gapminder <- read_csv("path-or-address-to-file.csv")

After importing data, the output may summarize the variables and their types. The dataset can be displayed in RStudio using:

View(gapminder)

Useful inspection functions

  • dim(gapminder) returns the number of rows and columns. In this example, the dataset has about 1,7041{,}7041,704 rows and 666 variables.

  • head(gapminder) displays the first few rows.

  • tail(gapminder) displays the last few rows.

  • names(gapminder) returns the variable names.

Inspecting a dataset early helps confirm that it imported successfully, shows its structure, and supports decisions about which data to analyze.


Cleaning and transforming data

Missing values

R represents a missing or unavailable value as NA. Missing values can affect calculations. For example, the mean of a vector containing NA will usually return NA, because R cannot calculate the result using all values as if they were present.

For calculations that support the na.rm argument, missing values can be excluded:

mean(age, na.rm = TRUE)

The default is generally na.rm = FALSE. Setting it to TRUE removes missing values from that calculation. This does not alter the original dataset; it changes how that particular calculation handles missing values. Analysts should consider why values are missing and whether excluding them is appropriate.

Filtering observations

The filter() function from dplyr selects rows that meet specified conditions. The filtered results can be saved as a new dataset.

For example, data can be selected for one year:

gapminder_2007 <- filter(gapminder, year == 2007)

Data can also be restricted to a continent:

gapminder_asia <- filter(gapminder, continent == "Asia")

Or selected using a numeric threshold:

gapminder_mega <- filter(gapminder, pop > 10000000)

The new object names are chosen by the analyst. Filtering is useful when the research question concerns a particular year, region, population, or other subset of observations.


Data visualization with ggplot2

Visualizations help people recognize patterns more quickly than they can from raw tables or lengthy reports. Figures can reveal distributions, differences, relationships, and unusual observations. They can also make findings easier to communicate.

Layered plotting

ggplot2 builds a plot in layers. A plot begins with the data and a mapping between variables and visual properties, such as the horizontal and vertical axes. A geometric layer then specifies how the observations should be drawn.

A scatterplot of GDP per capita and life expectancy can be started with:

ggplot(gapminder, aes(x = gdpPercap, y = lifeExp))

This establishes the data and axis mappings. A scatterplot layer adds points:

ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
  geom_point()

Additional settings can control the points’ appearance. For example, alpha controls transparency and size controls point size:

ggplot(gapminder, aes(x = gdpPercap, y = lifeExp)) +
  geom_point(alpha = 0.5, size = 2)

A visual property can also be mapped to a variable. Mapping point color to continent distinguishes groups:

ggplot(gapminder, aes(x = gdpPercap,
                      y = lifeExp,
                      color = continent)) +
  geom_point()

In this setting, the color represents a data category rather than being a fixed styling choice.

Other common plot types

  • Boxplots summarize a distribution by showing its median, spread, and potential outliers. They can compare a numeric variable across categories, such as life expectancy across continents.

  • Histograms show the distribution of a numeric variable by grouping values into intervals and displaying their frequencies. A histogram of life expectancy can show where observations are concentrated and how spread out they are.

A plot may reveal broad patterns—for example, a positive association between GDP per capita and life expectancy—before a formal model is fitted. Visual patterns are useful for forming questions, but they do not alone establish causation or statistical significance.


Descriptive statistics and statistical analysis

Summarizing data

The summary() function provides summaries of variables in a dataset. For numeric variables, it commonly reports values such as the minimum, median, mean, and maximum. For categorical or character variables, it displays information appropriate to those types.

Summaries can also be calculated by group. For example, life-expectancy summaries can be organized by continent using a grouping or “by” operation. Grouped summaries help compare the distributions and typical values of different categories.

Counting unique values

The dollar-sign operator $ accesses a named column in a data frame. For example, gapminder$country refers to the country variable.

The unique() function returns distinct values, and length() counts how many values are in a vector. Together, they can be used to count the number of distinct countries:

length(unique(gapminder$country))

In the example dataset, the number of distinct countries is 142142142.

Correlation

The cor() function calculates a correlation between numeric variables:

cor(gapminder$lifeExp, gapminder$gdpPercap)

The example analysis reports a positive correlation of about 0.580.580.58 between life expectancy and GDP per capita. This indicates that higher values of one variable tend to occur with higher values of the other in the dataset. Correlation describes association; it does not, by itself, show that one variable causes the other.

Independent-samples and paired t-tests

A t-test can compare means between two conditions or groups. Before running a test, the relevant observations should be selected and the data structure should match the intended design.

  • An independent-samples t-test compares the means of two separate groups. For example, life expectancy can be compared between observations from Europe and Asia.

  • A paired t-test compares two related measurements, such as measurements from the same units at two time points. The paired = TRUE argument requests a paired test.

When years are stored as numbers but represent categories or measurement occasions, they may need to be treated as factors for an analysis that uses them as categories. A paired comparison across years also requires observations to be correctly matched; merely selecting two years does not by itself ensure valid pairing.

A t-test output may include a test statistic, a ppp-value, a confidence interval, and an alternative hypothesis. A sufficiently small ppp-value can provide evidence against the null hypothesis of no difference under the assumptions of the test. It does not establish the size or practical importance of the difference on its own.

Linear models

The lm() function fits a linear model. A model can relate an outcome variable to one or more predictors:

mod <- lm(lifeExp ~ pop + gdpPercap + year,
          data = gapminder)
summary(mod)

In this example, life expectancy is the outcome, while population, GDP per capita, and year are predictors. The model is stored in the object mod; summary(mod) displays information about the fitted model.

A model summary can include:

  • Coefficients: Estimated relationships between the predictors and the outcome, along with uncertainty and significance information.

  • Residuals: Differences between observed outcomes and the values predicted by the model; they represent variation not captured by the fitted model.

  • Model-level tests: Information about whether the model as a whole improves on a baseline model, subject to the model’s assumptions.

  • Adjusted R2R^2R2: A measure of the proportion of variation accounted for by the model, adjusted for the number of predictors.

The example reports an adjusted R2R^2R2 of approximately 0.43920.43920.4392, meaning that the model accounts for about 44%44\%44% of the outcome’s variation under that model and dataset. This is a measure of model fit, not proof that the model is correct or that its predictors cause the outcome.

Model components can be extracted programmatically. For example, coefficients can be accessed through the model object. This is useful when results need to be reused, formatted, or incorporated into further computations.


Communicating and reproducing analyses

Readable and documented scripts

A script is more useful when other people can understand it. Helpful practices include:

  • Using consistent naming and formatting conventions.

  • Following a style guide when appropriate, while recognizing that teams may have their own standards.

  • Adding comments to explain the purpose of code and clarify analytical choices. Comments document the script but are not executed as commands.

  • Keeping related steps organized so the workflow is easy to follow.

Comments can explain what a line or section is intended to do, such as identifying a model as a regression predicting life expectancy from selected variables.

R Markdown

R Markdown allows code, explanatory text, and analysis output to be combined in one document. This can make it easier to produce a report that includes the code used to generate results alongside the results themselves. It supports reproducible communication because the document can be regenerated from its analysis.


Big data

Big data are important because many modern sources generate large and complex datasets. Examples include:

  • Brain imaging: Techniques such as fMRI and EEG can produce many measurements. In imaging data, the brain may be represented as a three-dimensional grid of voxels; a scan can contain millions of voxel-level measurements.

  • Genomic data: Genetic studies can measure thousands of features or more, depending on the data type and study design.

  • Wearable devices: Devices such as smartwatches can repeatedly record information such as heart rate over time.

  • Social networks: Online platforms generate large amounts of information through user activity and interactions.

A common contrast is between traditional experiments, which may have many participants but relatively few variables per participant, and high-dimensional data, which may have many measured features relative to the number of participants. Classical statistical methods are not automatically unsuitable for high-dimensional data, but the design creates challenges. Machine-learning methods can help select features, reduce dimensionality, or build predictive models, provided that the methods are appropriate and carefully evaluated.

Big data are not automatically better data. Data quality, sampling, measurement, missingness, and bias remain important regardless of dataset size.


Machine learning

What machine learning does

Machine learning uses algorithms to learn patterns from data and apply those patterns to tasks such as categorizing observations, estimating numeric outcomes, or finding structure. Rather than specifying every decision in advance, a learning method uses examples in the data to build a model.

More information can improve performance when it is relevant, reliable, and representative, but adding data does not guarantee a better model. The usefulness of an algorithm depends on the data, the learning task, the model assumptions, and the way performance is evaluated.

Three common machine-learning tasks

Classification

Classification assigns observations to categories. A classification model uses features of an observation to predict which class it belongs to. For example, a model might use measurements from a new case to predict which of several known categories best fits it.

Regression

Regression predicts a numeric outcome from input features. A model is learned from existing observations and then applied to new observations to estimate their outcomes. Statistical linear models and machine-learning regression methods share this general goal, though they may differ in how they are built and evaluated.

Clustering

Clustering groups observations based on similarities in their features. It is used to look for structure or patterns when the relevant groups are not already supplied as labels. A clustering result is not automatically a natural or meaningful set of categories; its interpretation depends on the data, method, and research question.

Supervised and unsupervised learning

  • Supervised learning uses both input features and known outcome labels during model development. Classification and regression are common examples. Once the model is learned, it can be used to predict outcomes for new observations.

  • Unsupervised learning uses input data without supplied outcome labels to identify patterns or structure. Clustering is a common example.

Classification and clustering are both concerned with grouping, but they differ in a key way: classification learns from known category labels, whereas clustering looks for groups without those labels.

Inference and prediction

Statistics and machine learning can both support inference and prediction, but they often emphasize different goals:

  • Inference aims to describe or test relationships and understand how a data-generating process may behave. Traditional statistical methods are often designed with this goal in mind.

  • Prediction aims to forecast outcomes for observations or situations not used to fit the model. Machine-learning methods are often designed and evaluated with predictive performance as a central goal.

The boundary between statistics and machine learning is not absolute. The same method may support both goals, but the methods, evaluation criteria, and interpretation should match the purpose of the analysis.


Why more data can mislead: the Google Flu Trends example

Google Flu Trends attempted to estimate flu activity using the frequency of flu-related searches. Early predictions appeared to correspond reasonably well with public-health estimates. However, media attention increased public awareness of the system, and people began searching for flu-related information for reasons other than having flu symptoms.

As a result, search activity changed partly because people knew about the prediction system. The model later overestimated flu activity relative to public-health records. This illustrates several important principles:

  • Data can change in response to the system using them. Public awareness affected the behavior that generated the search data.

  • A large dataset can still be biased or poorly aligned with the quantity being estimated.

  • The relationship between a feature and an outcome can change over time.

  • Predictions should be compared with relevant external evidence and assessed for changes in the data-generation process.

Big data and machine learning complement traditional data collection and analysis; they do not replace careful study design or critical evaluation.


Key principles for research practice

  • R supports reproducible research by recording analytical procedures in scripts.

  • A complete workflow includes importing, cleaning, transforming, visualizing, modeling, and communicating data.

  • Learning R can help researchers prepare for complex and high-dimensional data, but a large dataset does not guarantee reliable conclusions.

  • Researchers should assess whether the data and methods are legitimate for the question being asked.

  • Big data can help generate new hypotheses; carefully designed studies can then investigate those hypotheses.

  • R’s user community and online resources can support learning, troubleshooting, and discovery of packages and methods.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent