1. Home
  2. Explore
  3. Computer Science
  4. End-to-End Data Science

Study methods

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

End-to-End Data Science

End-to-End Data Science with R

Data science is more than writing code or calculating statistics. It is a process for turning a meaningful question into evidence that can support better decisions. In education, that process matters because data tools should ultimately serve students, educators, and communities.

This lesson introduces the R programming language, the RStudio environment, packages, and R Markdown. It then walks through a complete data-analysis workflow using school enrollment data: asking a planning question, importing and preparing data, visualizing patterns, calculating summary statistics, interpreting the results, and communicating the findings responsibly.

Data Science as a Tool for Service

A data scientist may enjoy programming, solving puzzles, and exploring patterns. However, technical skill alone does not guarantee useful work. If an analysis answers a question that matters only to the analyst, the result may be technically impressive but practically irrelevant.

In education, data science should be connected to meaningful problems such as:

  • Planning services for schools and districts
  • Understanding differences among student groups
  • Supporting equity in special education
  • Allocating materials or staff
  • Identifying patterns that can improve student outcomes
  • Helping educators make informed decisions

The most important starting point is therefore not a programming language. It is a useful question.

For example, a county office planning a training service may need to know how many schools each district contains. That information could help determine how many training materials, staff members, or resources are needed.

A weak question might be, “What interesting patterns can be found in this dataset?” A stronger question is, “How many schools does each district have, and can one standard amount of materials serve every district adequately?”

The second question is useful because it is tied to a decision.

Effective data science connects technical methods to problems that matter to other people.

Think About It

A useful reflection is: What decision in an educational setting could be improved by collecting and analyzing data?

The Main Tools

The workflow uses four connected tools:

  1. R
  2. RStudio
  3. R packages
  4. R Markdown

Each has a different role.

R: The Statistical Programming Language

R is a programming language designed especially for statistical analysis, data manipulation, and visualization. The analyst writes instructions in R, and R executes those instructions on data.

A programming language differs from a spreadsheet because the analyst describes the operations that should occur rather than manually performing each operation. For example, instead of selecting cells and repeatedly applying calculations, an analyst can write code that:

  • Imports a dataset
  • Filters it to a particular county
  • Removes duplicate records
  • Counts schools by district
  • Calculates averages and standard deviations
  • Produces a chart
  • Generates a report

R is open source, which means that it can generally be used without paying for the language itself. Its open-source structure also allows a large community of users to develop and share tools.

RStudio: The Working Environment

RStudio is an application used to write and manage R code. R is the language; RStudio is the environment in which the analyst works with that language.

The distinction can be understood through a writing analogy:

  • Spanish is a language.
  • Google Docs is a writing environment.
  • A PDF or printed document is a shareable output.

Similarly:

  • R is the statistical language.
  • RStudio is the coding and analysis environment.
  • A report, webpage, PDF, or GitHub project can be the shared output.

RStudio makes it easier to:

  • Write and run code
  • View datasets
  • Inspect results
  • Organize files
  • Install and load packages
  • Create charts
  • Build reports
  • Share completed analyses

RStudio is not itself the statistical language. It helps the analyst work with R more efficiently.

R Packages: Extending R

The basic installation of R provides many capabilities, but analysts often need additional tools. Packages are collections of code that extend R’s functionality.

Packages can support tasks such as:

  • Preparing and reshaping datasets
  • Fitting statistical models
  • Creating graphics
  • Producing reports
  • Navigating files
  • Automating repeated analyses

Most R packages are developed and shared by the R community. This community-based system allows analysts to add tools according to the needs of a particular project.

The Tidyverse

The tidyverse is a group of R packages that work together for common data-science tasks. It includes tools for:

  • Cleaning and organizing data
  • Filtering rows
  • Selecting variables
  • Counting observations
  • Summarizing data
  • Creating visualizations

The visualization package ggplot2 is part of the tidyverse. The example analysis also uses a package called here, which helps organize file paths and makes analysis scripts easier to transfer between computers or users.

Loading packages makes their functions available for use in the current analysis.

library(tidyverse)
library(here)

R Markdown: Combining Explanation and Code

R Markdown is a document format that combines written explanation, code, and results in one place.

An R Markdown document can contain:

  • Narrative text
  • R code
  • Tables
  • Charts
  • Statistical results
  • Conclusions

The analyst can run code inside the document and then knit the document. Knitting means that R executes the code and dynamically inserts the resulting tables, charts, and output into a finished report.

This creates an important connection between the analysis and the explanation. The report does not merely state a result; it can also show how that result was produced.

R Markdown resembles a word-processing document because it supports features such as:

  • Editable text
  • Organized sections
  • Spell checking
  • Formatted output

Its special advantage is that the analysis code and the written interpretation remain connected.

For example, an R Markdown report might include:

  1. A description of the research question
  2. Code importing the data
  3. Code preparing the data
  4. A graph showing district sizes
  5. Calculations of the mean and standard deviation
  6. A written interpretation of the findings

This structure improves transparency and reproducibility.

R Scripts and R Markdown Documents

An R script is primarily a file containing R code. It is useful when the main goal is to execute a sequence of commands or produce a data file such as a CSV.

An R Markdown document includes both code and narrative. It is especially useful when the analysis needs to be communicated to other people through text, tables, graphics, and conclusions.

A practical workflow may use both:

  • A separate R script can contain a long, complicated data-preparation process.
  • An R Markdown file can call that script and present the results clearly.

This separation can keep a report readable while preserving reusable preparation code. An analyst may also begin exploration in an R script and later move the polished analysis into an R Markdown document.

The appropriate choice depends on the purpose of the work.

Think About It

A useful reflection is: Would a particular analysis be more useful as a private working script, a shareable report, or a combination of both?

The End-to-End Analysis Workflow

A typical data-analysis workflow includes these stages:

  1. Identify a question.
  2. Import relevant data.
  3. Prepare the data for the question.
  4. Choose an analytical method.
  5. Visualize important patterns.
  6. Analyze the data.
  7. Interpret and communicate the results.

The order matters. A calculation cannot answer a question correctly if the data has not been prepared to match that question.

Stage 1: Identify the Question

The example question is:

How many schools do districts in San Diego County have on average?

This question is part of a larger planning problem. A county office wants to provide a training service to all districts, but resources are limited. The analysis should help determine whether districts are similar enough that one uniform amount of material could be purchased for everyone.

Several related questions follow:

  • Do districts have similar numbers of schools?
  • If they differ, how large are the differences?
  • Would one standard number of materials be appropriate?
  • Would larger districts require customized support?

These questions define what data is needed and what calculations will be useful.

Stage 2: Import the Data

The analysis uses publicly available enrollment data from the California Department of Education. The data contains records for schools throughout California.

A tab-separated values file can be imported using read_tsv().

enroll <- read_tsv("data-file.tsv")

The object enroll stores the imported dataset in R’s memory. The assignment operator <- gives the dataset a name so that it can be referenced later.

After importing the dataset, R reports that it contains:

  • 131,616131{,}616131,616 rows
  • 232323 columns

In R, a dataset is often called a data frame or tibble. A row represents an observation, and a column represents a variable.

At this point, the dataset includes records for many counties and schools. It is much larger than what is needed for the specific question.

Viewing the Data

Unlike a spreadsheet, R does not automatically display the entire dataset in a grid. The View() function opens the data in a spreadsheet-like display.

View(enroll)

This allows the analyst to inspect:

  • Variable names
  • Values in individual columns
  • Repeated records
  • County names
  • District names
  • School names
  • The overall structure of the dataset

Inspecting the data is essential because the dataset may not be organized in the exact form required for the analysis.

Understanding the Dataset’s Structure

The imported data does not contain one row per school. Instead, each row represents a combination of characteristics such as:

  • County
  • District
  • School
  • Ethnicity
  • Gender

Because a single school may have multiple ethnicity and gender records, the same school appears many times.

For example, if a school has records for several demographic categories, it will occupy multiple rows. Counting rows at this stage would count demographic records, not schools.

This is a central principle of data analysis:

The meaning of a count depends on what one row represents.

If each row represented one school, counting rows would produce the number of schools. Because each row instead represents a more detailed subgroup record, the data must be prepared first.

Stage 3: Prepare the Data

Data preparation means changing the dataset into a form that matches the analytical question.

The question concerns schools in San Diego County. Therefore, the first preparation step is to retain only records from that county.

Filtering to One County

The filter() function keeps rows that satisfy a condition.

sd <- enroll %>%
  filter(county == "San Diego")

The filtering operation reduces the dataset from 131,616131{,}616131,616 rows to 10,87610{,}87610,876 rows. The remaining records belong only to San Diego County.

Filtering is useful because it:

  • Removes irrelevant observations
  • Makes the dataset easier to inspect
  • Focuses later calculations on the intended population
  • Reduces unnecessary processing

Keeping One Row per School

The next task is to remove repeated records so that each school appears once.

The distinct() function keeps unique combinations of selected variables.

sd <- sd %>%
  distinct(district, school)

The combination of district and school is used rather than school name alone. This is important because two schools in different districts might have the same name. The pair of values identifies the school more reliably.

After this operation, the dataset contains:

  • One row per unique district-school combination
  • 795795795 schools in total
  • No repeated demographic records for the same school

For example, if a school named “Wolf Canyon” originally appeared many times because of demographic categories, distinct(district, school) reduces it to one record.

Why Preparation Comes Before Counting

If the analysis counted the original rows, a school with many demographic records would contribute more to the count than a school with fewer records. That would produce a misleading estimate of district size.

The preparation step ensures that:

  • One school contributes one row.
  • A district appears once for every school it contains.
  • Counting district appearances gives the number of schools in that district.

This illustrates why a question must be understood before code is written. The code is not merely manipulating data; it is aligning the structure of the data with the meaning of the question.

Think About It

A useful reflection is: What would go wrong if a dataset containing multiple records per student were used to count students without first removing duplicate student records?

Stage 4: Count Schools by District

Once the dataset contains one row per school, the number of schools in each district can be calculated.

The count() function counts how many rows belong to each value of a variable.

school_count <- sd %>%
  count(district)

The result contains:

  • A column listing districts
  • A column named n showing the number of rows associated with each district

Because every row now represents one school, the value of n represents the number of schools in that district.

For example, if “Chula Vista” appears 404040 times in the prepared dataset, that means Chula Vista has 404040 schools represented in the data.

The analyst can sort the results to place the largest districts first.

school_count <- sd %>%
  count(district, sort = TRUE)

Sorting makes major patterns easier to notice. San Diego Unified appears at the top with 223223223 schools, while Chula Vista is also large but has fewer schools.

This initial inspection already suggests that districts do not all have similar sizes.

Stage 5: Visualize the Pattern

Tables are useful, but graphs often make differences easier to understand. Human perception is especially effective at comparing the lengths of bars.

A bar chart can show the number of schools in each district. However, displaying all approximately 505050 districts may make the graph crowded. A clearer first view is to display only the largest districts.

Selecting the Largest Districts

The min_rank() function can rank values. Filtering for ranks less than or equal to 101010 selects the largest values when the data is ranked in descending order.

top_10 <- school_count %>%
  filter(min_rank(desc(n)) <= 10)

Depending on tied values, the result may contain slightly more or fewer than exactly 101010 rows. In the demonstration, the output contained 999 districts because of the way the ranking and ties worked.

The purpose is not to force an exact number of districts. The purpose is to reduce the dataset enough to make the visual pattern readable.

Building a Chart with ggplot2

The ggplot2 package builds graphics in layers. The basic structure specifies:

  1. The dataset
  2. Which variable goes on the horizontal axis
  3. Which variable goes on the vertical axis
  4. The type of geometric shape to draw

A basic bar chart can be written as:

ggplot(top_10, aes(x = district, y = n)) +
  geom_bar(stat = "identity")

Here:

  • top_10 is the dataset.
  • district identifies the categories.
  • n gives the number of schools.
  • geom_bar() draws the bars.
  • stat = "identity" tells ggplot2 to use the existing values of n rather than count observations again.

Reordering the Bars

A chart is easier to interpret when districts are arranged from smallest to largest or largest to smallest.

ggplot(top_10, aes(x = reorder(district, n), y = n)) +
  geom_bar(stat = "identity")

The reorder() function arranges the district labels according to the number of schools.

Flipping the Coordinates

Long district names can be difficult to read along a horizontal axis. The coord_flip() function exchanges the horizontal and vertical directions.

ggplot(top_10, aes(x = reorder(district, n), y = n)) +
  geom_bar(stat = "identity") +
  coord_flip()

The resulting horizontal bar chart makes the district names easier to read and makes the differences in bar length easier to compare.

The visualization clearly shows that San Diego Unified has substantially more schools than the next-largest districts. This matters because an average alone may hide the fact that the districts vary dramatically.

Think About It

A useful reflection is: Why might a chart reveal an important planning problem that a single average would conceal?

Stage 6: Calculate Summary Statistics

The analysis uses two summary statistics:

  • The mean, or average
  • The standard deviation, a measure of variation

The Mean

The mean is calculated by adding all values and dividing by the number of values.

For district school counts, the mean represents the average number of schools per district.

The R function mean() calculates the mean.

The Standard Deviation

The standard deviation measures how spread out the values are around the mean.

A small standard deviation means that values tend to be relatively close to the average. A large standard deviation means that values differ substantially from one another.

In the planning example, the standard deviation helps answer a question that the mean alone cannot answer:

Are districts reasonably similar in size, or is the average hiding major differences?

Calculating the Mean and Standard Deviation

The summarise() function reduces many rows to a smaller summary table.

school_summary <- school_count %>%
  summarise(
    avg_schools = mean(n),
    standard_dev = sd(n)
  )

The result is one row containing:

  • An average of approximately 161616 schools per district
  • A standard deviation of approximately 323232 schools

The standard deviation is larger than the mean. That signals substantial variation among districts.

Interpreting the Results

A simple report might state:

San Diego districts have approximately 161616 schools on average.

That statement is technically accurate but incomplete. The standard deviation and visualization show that the districts are not clustered closely around 161616 schools.

San Diego Unified has 223223223 schools, while other districts have far fewer. Thus, treating 161616 as a standard number for every district would be misleading.

For a statistically knowledgeable audience, the difference between San Diego Unified and the next-largest district was described as approximately seven standard deviations. This indicates an exceptionally large difference relative to the overall spread of district sizes.

The practical consequence is important:

  • A uniform allocation might provide too much to small districts.
  • The same allocation might leave a large district without enough materials.
  • Planning should account for district size rather than relying only on the average.

A summary statistic should be interpreted alongside the distribution of the data and the decision the analysis is meant to support.

Why Use Code Instead of a Calculator or Spreadsheet?

For a small calculation, a calculator or spreadsheet may be the most efficient choice. The goal is not to replace every tool with R.

If the task is simply to calculate one average and one standard deviation from a small table, manually performing the calculation may be perfectly reasonable.

The major advantage of code appears when the analysis must be repeated, expanded, or shared.

Reproducibility: Sharing the Recipe

A spreadsheet often communicates the final product. Code can communicate both:

  • The final result
  • The procedure used to produce the result

This can be compared to baking:

  • A spreadsheet may provide the finished cookies.
  • Code provides the cookies and the recipe.

The recipe allows another analyst to modify the process. For example, the other analyst could replace one ingredient, change the quantities, or apply the recipe to a different batch.

Similarly, code allows an analyst to:

  • Change the county
  • Change the year
  • Add another variable
  • Alter the visualization
  • Recalculate the statistics
  • Apply the same workflow to a new dataset

Scale

The same code could be used to:

  • Analyze ten years of data
  • Compare every county in California
  • Examine changes in district size over time
  • Generate a separate report for each county
  • Produce standardized reports for many organizations

These tasks would become increasingly difficult and error-prone if performed manually in separate spreadsheets.

The initial investment in learning and writing code may take longer than a one-time manual calculation. However, the payoff grows when the work must be repeated or expanded.

Transferability

Code can also be shared with colleagues. If the script is written clearly and the file paths are organized properly, another analyst can run the same workflow on a different computer or dataset.

This is one reason the here package can be useful: it helps make file references more consistent and makes an analysis easier to transfer.

Transparency

R Markdown adds another advantage: the written explanation, code, graphics, and conclusions can remain together.

A reader can inspect:

  • What question was asked
  • Which data was used
  • How the data was prepared
  • Which methods were selected
  • What the results were
  • How the results were interpreted

This makes the analysis easier to evaluate and reproduce.

Think About It

A useful reflection is: When would the ability to rerun an analysis be more valuable than the convenience of completing it manually one time?

Choosing Questions That Matter

Technical competence does not replace communication and collaboration.

An analyst may spend a long time learning programming, preparing data, creating a report, and calculating an impressive result. Yet the work can still fail if the analyst never checks whether the question is important to the people who will use the answer.

A meaningful analysis should be connected to the needs of its intended audience.

Before beginning a project, an analyst should consider:

  • Who will use the results?
  • What decision will the results inform?
  • What problem is the analysis intended to solve?
  • What would change if the findings were different?
  • Are the available data appropriate for the question?
  • How should the results be communicated to nontechnical audiences?

The purpose of data science in education is not simply to produce technically correct output. It is to help communities make better decisions for students.

An analysis can be mathematically correct and still fail as practical work if it does not address a real concern.

Communicating with Nontechnical Audiences

Data science can become isolating when analysts work only with other programmers or statisticians. Sharing results with educators, administrators, families, and community members is essential because these groups often understand the practical context better than the analyst does.

Nontechnical audiences may not need every line of code. They do need to understand:

  • The question
  • The main finding
  • The evidence supporting it
  • The limitations of the analysis
  • The decision implications

For the district-size example, a useful explanation would combine:

  1. The average of approximately 161616 schools per district
  2. The standard deviation of approximately 323232
  3. A chart showing the very large districts
  4. A warning that the average should not be treated as a uniform allocation
  5. A recommendation to plan resources according to district size

This is more useful than presenting a number without context.

A Complete Conceptual Workflow

The entire analysis can be summarized as follows:

1. Begin with a meaningful question

The question should be connected to a practical decision rather than chosen solely because the dataset is available.

2. Find appropriate data

The data should contain the information needed to answer the question and should represent the relevant population.

3. Inspect the structure

The analyst must determine what one row represents and whether records are repeated for demographic categories, years, locations, or other subgroups.

4. Prepare the data

Filtering removes irrelevant records. distinct() removes duplicate combinations. Other transformations may be needed in different projects.

5. Create the correct unit of analysis

If the question concerns schools, the dataset must be organized so that school counts are not distorted by multiple records per school.

6. Summarize the data

Functions such as count(), mean(), and sd() reveal basic patterns and variation.

7. Visualize important differences

Graphs help analysts and audiences see patterns that may not be obvious in a table.

8. Interpret results in context

A numerical result must be connected to the decision it is intended to support. An average is not automatically a recommendation.

9. Communicate clearly

The final report should explain the question, method, findings, limitations, and practical implications.

10. Preserve the workflow

Saving the code and the data allows the analysis to be checked, repeated, adapted, and scaled.

Comprehensive Review

R is a statistical programming language used to analyze, transform, visualize, and report data. RStudio is the application that helps analysts write and manage R code. R packages extend R by adding specialized functions, and the tidyverse provides a collection of tools for common data-science tasks. R Markdown combines narrative, code, graphics, and results in a reproducible report.

An end-to-end analysis begins with a meaningful question. In the district-size example, the question concerns the average number of schools per district and whether a uniform resource allocation would be appropriate.

The raw dataset cannot be counted immediately because each school appears in multiple rows for different demographic categories. Filtering limits the data to San Diego County, and distinct(district, school) creates one row per unique school. Once the data is prepared, count(district) determines how many schools belong to each district.

A bar chart created with ggplot2 makes the differences visible. The summary statistics show an average of approximately 161616 schools per district and a standard deviation of approximately 323232 schools. Because the variation is large, the average alone is not a suitable basis for distributing identical amounts of materials.

Code is especially valuable when work must be repeated, shared, or scaled. It preserves the analytical recipe, supports reproducibility, and allows the same workflow to be applied across years, counties, or customized reports. Most importantly, data science should remain connected to human purposes: the strongest analysis is not merely the one that uses sophisticated tools, but the one that answers a question that genuinely supports students and communities.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent