R Statistics and Machine Learning


R Statistics and Machine Learning

Corey
Welcome, everyone. This is a short, hands-on workshop about statistics and machine learning with R. We’ll spend most of our time learning R basics and working with data, then touch on visualization, statistical models, big data, and machine learning.

Michael
And if you’re new to programming, you’re in the right place. We’ll build up step by step, and the goal is to understand what the commands do—not just copy them from the handout.

Corey
Let’s start with the big question: why learn programming for research? A useful way to think about it is that data skills help us understand information, process it, find value in it, visualize it, and communicate what we learn. Those skills matter across academic and professional settings.

Michael
Why not just use a menu-based statistics program? Those tools can be convenient, especially for straightforward analyses. But a research workflow often includes data cleaning and preparation before the analysis, and doing those steps separately—for example, in a spreadsheet—can make it harder to reproduce exactly what happened.

Corey
A script can bring those steps together: import the data, prepare it, run the analysis, and create the figures. That helps with reproducibility because the instructions are recorded, and it helps with automation because you can rerun the same process instead of repeating a long series of clicks.

Michael
Scripts also make the method easier to inspect and discuss. If someone gives you a result, a written script can show the steps used to get it. That’s useful when you’re reviewing another researcher’s work, explaining your own procedure, or trying to understand a method that a paper describes only vaguely.

Corey
So why choose R? It’s free and open source, and it has a large community, including many researchers. That means people share help and contribute packages—collections of functions—that can bring newer methods into your work.

Michael
R is also a scripting language, which supports the reproducibility and automation we’ve been talking about. It’s flexible and extensible, and it runs on Mac, Windows, and Linux. Other languages, such as Python and C++, are also useful; R is especially suited to statistical work.

Corey
For this workshop, we’ll use RStudio. R itself is the language, while RStudio is a free development environment that gives you a convenient interface for writing and running R code. You can download R from r-project.org and RStudio Desktop from rstudio.com.

Michael
Once RStudio is open, you’ll usually see a text editor, a console, a workspace or environment pane, and a pane for files, help, and plots. The console is where you can enter commands and see results. The text editor is where you can write and save a script, while the other panes help you inspect objects and outputs.

Corey
Let’s try a simple command in the console: 14 plus 3. R returns 17. You can also try 10 divided by 12, 3 times 18, and 3 to the power of 3. R can act as a calculator, and that same ability to work with numbers is part of what makes it useful for statistics.

Michael
For other mathematical operations, you can call functions. For example, log of 36 uses the log function, and the square root of 39,204 uses sqrt. A function takes an input, performs an operation, and returns a result.

Corey
R can also check logical statements. The double equals sign asks whether two things are equal, while an exclamation mark followed by an equals sign asks whether they differ. So 50 == 50 + 1 is false, and 50 != 50 + 1 is true. You can also compare values and combine logical conditions.

Michael
A core idea in R is that you work with objects. Two important kinds are data, which stores information, and functions, which operate on data. You assign a value to an object with the assignment arrow, such as my_height <- 177. That stores the value, even though the assignment itself doesn’t necessarily print a result.

Corey
You can combine values into a vector with c, short for combine. For example, my_heights <- c(177, 156, 189, 200) puts four numbers into one object. You could also store a weight, then use the height and weight data as inputs to a function that calculates BMI.

Michael
R has several common data structures. A vector holds values of the same basic type, such as a character vector of names or a numeric vector of scores. The class function tells you the type: class(names) might return character, while class(IQ_scores) would return numeric.

Corey
A list can combine different objects, including vectors of different types. For instance, you could make a list containing both the names vector and the IQ scores vector. When you inspect the list, its elements are kept as separate components.

Michael
A matrix is arranged in rows and columns and is important because many statistical and machine-learning operations use matrix structures. You can create one with the matrix function and specify the number of rows or columns. One small but crucial R detail: names are case-sensitive, so an object called X is not the same as one called x.

Corey
For tabular data, a data frame is especially useful. You can create one from the names and scores vectors with data.frame(names, IQ_scores). The result is a table where each vector becomes a column and each matching position becomes a row.

Michael
Now let’s look at functions you write yourself. A function has a name, inputs—called arguments—and instructions describing what to do with those inputs. One classic first example is a greeting function that takes no arguments and prints “Hello World!” The quotation marks tell R that those words are text, not the name of an object.

Corey
You can also write a BMI function. It takes height and weight as inputs and calculates weight divided by height squared, with height expressed in meters. In the workshop example, a person who is 1.8 meters tall and weighs 70 kilograms has a BMI of about 21.6.

Michael
And a function can do more than return a number. You can use conditional statements to check the result and print a message—for example, a different message depending on which range the BMI falls into. That illustrates how programming lets you combine calculations with decision-making.

Corey
For practice, you can write another function that takes two integers and prints their sum and product. Then try a function that takes a numeric vector and prints its mean and standard deviation, with an optional setting to print the median too.

Michael
When you write a multi-line function, make the structure clear: use braces around the function body and put separate instructions on separate lines. You can also give an argument a default value. For example, print.median = FALSE means the median is left out unless the user explicitly asks for it by setting print.median = TRUE.

Corey
Let’s move from individual R objects to the full data workflow. A useful data model is: import data, tidy and transform it, visualize it, model it, and communicate the results. You may repeat parts of that process as your exploration raises new questions.

Michael
It’s easy to focus only on the model—the statistical test or regression. But importing, cleaning, and reshaping data are also essential, and they affect what you can analyze. The tidyverse is a collection of R packages designed to help with common data-science tasks.

Corey
The tidyverse includes readr for importing data, dplyr for manipulating tables, tidyr for tidying data, and ggplot2 for visualization, among others. You install it with install.packages("tidyverse") and load it in a session with library(tidyverse). Installation gets the package onto your computer; loading makes its functions available.

Michael
For the workshop, we’ll read a CSV file of Gapminder data from an online source. The read_csv function imports it. The table has columns for country, year, population, continent, life expectancy, and GDP per capita.

Corey
You can inspect the imported data with View(gapminder). The dim function reports its dimensions—the data has roughly 1,700 rows and six columns. head shows the first six rows, tail shows the last six, and names lists the column names.

Michael
Cleaning matters even when you’re just calculating a simple summary. In R, NA represents a missing or unavailable value. If a vector contains NA, mean(age) may return NA rather than a mean based only on the observed values.

Corey
If that fits your analysis, you can ask the mean function to remove missing values using na.rm = TRUE. The default is FALSE, so it’s important to make the choice explicit. Handling missing data is part of preparing the data, not a detail to ignore.

Michael
To select rows, use filter. For example, filter the Gapminder table to keep only rows where year equals 2007, or where continent equals "Asia." You can also filter for population greater than ten million. The result can be saved as a new data frame with a descriptive name.

Corey
After preparing the data, visualization helps us see patterns and communicate them. ggplot2 builds graphics in layers. You start by specifying the data and mapping variables to visual roles—for example, GDP per capita on the x-axis and life expectancy on the y-axis.

Michael
Then add a geometric layer. geom_point makes a scatter plot, with one point for each row in the data. You can adjust the point size and transparency with settings such as size and alpha, and map color to continent to distinguish the groups.

Corey
Other geometries answer different questions. A box plot can compare the distribution of life expectancy across continents, showing features such as the median and spread, along with possible outliers. A histogram shows how often values fall into ranges; for example, it can display the distribution of life expectancy.

Michael
A more elaborate plot can combine several cues, such as GDP per capita, life expectancy, continent, and population. A figure like that can reveal patterns at a glance—for example, the data show a general association between higher GDP per capita and longer life expectancy. The plot helps generate questions, but it doesn’t by itself explain why a pattern occurs.

Corey
Once we’ve explored the data visually, we can calculate descriptive summaries. The summary function gives information for each variable. For numeric columns such as population, life expectancy, and GDP per capita, it reports summaries including the mean and median.

Michael
To summarize by group, you can use the by function with continent as the grouping index and summary as the function. To count distinct countries, select the country column with the dollar sign, use unique to find its distinct values, and use length to count them. In this dataset, that count is 142.

Corey
We can also measure the association between two numeric variables. The cor function calculates a correlation—for example, between life expectancy and GDP per capita in this dataset. The workshop result is about 0.58, a positive correlation. That describes an association; it doesn’t establish that one variable causes the other.

Michael
For a group comparison, the workshop filters the data to Europe and Asia and uses a t-test to compare life expectancy. The reported difference is statistically significant, and the negative t-value—given the way the groups are ordered in that test—indicates higher life expectancy for Europe in this comparison.

Corey
You can also compare measurements from two years with a paired t-test, using data from 2002 and 2007. In the example, the year is converted to a factor so it is treated as categorical, and paired = TRUE requests a paired test. The reported result indicates a statistically significant difference between the years.

Michael
For a model with several predictors, lm fits a linear model. The example models life expectancy using population, GDP per capita, and year. Saving the model in an object lets you inspect it later with summary(mod), which reports coefficient estimates, tests, residuals, and measures of model fit.

Corey
The coefficients describe the model’s estimated relationships, and the summary also reports an adjusted R-squared. In this example it is about 0.439, meaning the model accounts for around 44 percent of the variation in the outcome, after adjustment. You can also extract specific pieces, such as the coefficients, from the model object.

Michael
The last step is communication. Write scripts so another person can follow them: use a consistent style, add comments explaining important steps, and make clear what each analysis is doing. R Markdown can combine code and results in a document, though we won’t explore it in detail today.

Corey
Now, why discuss big data? Research and everyday technologies can generate large, complex datasets—for example, brain imaging, wearable-device measurements, and social-network activity. The key difference from many traditional experiments is often the shape of the data: experiments may have many participants and relatively few variables, while some big-data settings have many variables and fewer participants.

Michael
That high number of variables can create challenges for traditional statistical approaches. Machine-learning methods can help identify useful features and build predictive models. But big data isn’t automatically better data: what matters is the quality and relevance of the measurements, not just how much information you collected.

Corey
Machine learning refers broadly to algorithms that learn patterns from data rather than following only a fixed, hand-written set of decisions. More relevant information can sometimes improve performance, but the result still depends on the data and the method.

Michael
Three common machine-learning tasks are classification, regression, and clustering. Classification assigns an observation to a category based on its features. Regression predicts a numeric outcome. Clustering looks for similarities and hidden groupings in data without starting with known outcome labels.

Corey
That last distinction connects to supervised and unsupervised learning. Classification and regression are supervised: the training data include both input features and known outcomes, so the model can learn to predict outcomes for new cases. Clustering is unsupervised: it groups data using the inputs without an outcome variable to predict.

Michael
Statistics and machine learning can both support inference and prediction. Classical statistical modeling is often used to represent a data-generating process, test a hypothesis, and understand how a system behaves. Machine learning is often especially useful for predicting outcomes that haven’t been observed yet.

Corey
The boundary isn’t absolute, and neither approach replaces the other. More data can be useful, but data collection still needs to be thoughtful. A well-chosen, carefully measured dataset can be more informative than a larger dataset that captures the wrong signals.

Michael
The Google Flu Trends example makes that caution concrete. Google used flu-related searches to estimate flu activity, and its early predictions tracked the CDC’s reports fairly well. But when news coverage made people more aware of the tool, searching behavior could change—even when a person’s search wasn’t a reliable sign of having the flu.

Corey
That shift contributed to Google Flu Trends later predicting more flu activity than the CDC’s reported data. The lesson is that the process generating your data can change, especially when people react to the measurement or prediction itself. More observations don’t automatically solve that problem.

Michael
So the main takeaways are: R supports reproducible research by making analytical steps explicit; it can bring data preparation, analysis, and visualization into one workflow; and it can help you work with large datasets. But always consider whether your method and measurements are appropriate.

Corey
Big data and machine learning can be especially useful for discovering patterns and generating new hypotheses. Those hypotheses can then be tested with carefully designed studies. And when you get stuck with R, there are online resources and communities—including CRAN, Stack Overflow, and R-bloggers—that can help you find documentation and answers.

Michael
That’s our tour: from R’s basic objects and functions, through a complete data workflow, to statistical modeling and machine learning. The most important habit is to make your steps clear enough that you—and someone else—can understand how you got from raw data to a result.

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