To build summary code in RStudio, you write an R script that imports your data, inspects its structure, and then applies summary functions such as summary(), dplyr::summarise(), or table() depending on whether your columns are numeric or categorical. The key condition is that the code must match your data's actual types and grouping: a numeric summary and a frequency count answer different questions and use different functions. This guide walks through a reliable order of operations, from loading data to exporting results, with checks at each stage so you can tell whether the output is trustworthy.

Start With the Project and Data Prerequisites

Before typing summary code, set up a working environment that keeps paths and outputs organized. In RStudio, create a project (File > New Project) so that file paths are relative to the project folder rather than your whole computer. Put the data file in a data/ subfolder and plan a scripts/ folder for your .R file. Working inside a project means read.csv("data/survey.csv") resolves correctly on any machine where the project folder lives, which matters the moment you share the script with a colleague.

Confirm three things about your data file before writing any summary logic. First, know the file format—CSV, Excel, or something exported from a database—because each needs a different import function. Second, know whether the first row holds column names and what delimiter is used. Third, have a sense of the column meanings, because a column stored as text that should be numeric will silently produce useless summaries. If you don't know the format, open the file in a plain text editor first; seeing the raw rows prevents most import surprises.

Load the Tidyverse and Read the Data

Most summary work in R benefits from the tidyverse collection, which bundles readr, dplyr, and tidyr under one load command. Install it once with install.packages("tidyverse"), then load it in every session with:

Read a CSV with read_csv("data/yourfile.csv"), or use read.csv() from base R if you prefer no dependencies. For Excel files, the readxl package's read_excel() function handles .xlsx files. Assign the result to an object so you can reuse it:

If the import throws a parsing warning about column types, don't ignore it. read_csv() prints the guessed type for each column; a numeric column read as character usually means stray text, currency symbols, or thousands separators. Fix the import with the col_types argument or clean the column afterward, rather than proceeding into summaries that will mislead you.

Inspect Structure Before Summarizing

Summary code is only as good as your understanding of the data frame. Run a short inspection block immediately after import:

glimpse() shows every column with its type and the first few values, which catches character columns that should be numeric. dim() reports rows and columns so you can confirm nothing was dropped at import. colSums(is.na(raw_data)) counts missing values per column; a column that is 90 percent empty will produce a summary that looks precise but describes almost nobody.

Decide at this point which columns are measures (numeric) and which are categories (factors or character). This split drives every later step, because numeric summaries use means, medians, and ranges, while categorical summaries use counts and proportions.

Build the Core Summary Script, Step by Step

The following sequence produces a complete, runnable summary script. Treat it as a template and adapt column names to your data.

1: Load packages. Start the script with library(tidyverse). Keeping library calls at the top makes the script reproducible and easy to debug. 2: Read the data. Assign the import to raw_data as shown above. 3: Clean types. Convert known numeric columns that imported as text with mutate(across(c(age, income), as.numeric)), and convert category columns to factors with mutate(dept = factor(dept)) when you want consistent ordering in tables. 4: Handle missing values deliberately. Either filter with filter(!is.na(income)) before summarizing that column, or pass na.rm = TRUE to functions that support it. State the choice in a comment so future readers know why row counts differ. 5: Summarize numeric columns. Use summary(raw_data$income) for a quick five-number summary plus mean and missing count, or build a tidy table with summarise(). 6: Summarize categorical columns. Use count(raw_data, dept) for frequencies or table(raw_data$dept) in base R for a quick cross-tab. 7: Group when needed. Combine group_by() and summarise() to get per-group statistics, such as average income by department. 8: Export results. Write the summary table with write_csv(summary_table, "output/summary.csv") so the numbers persist outside the console.

After running steps 1 through 5, expect the console to print a compact statistical profile of each numeric column. After step 6, expect a small table of category counts. The success check is simple: the row counts in your frequency table should sum to the number of non-missing rows in the original data frame. If they don't, a filter or a factor conversion changed the population, and you should investigate before trusting the numbers.

Summarize Numeric Columns With Base R and dplyr

Two idioms cover almost every numeric summary. Base R is fastest for a first look:

summary() returns minimum, first quartile, median, mean, third quartile, maximum, and the count of missing values. It is ideal for a quick profile, but its output is plain text, not a data frame you can export or reshape.

The dplyr approach produces a structured table:

The n column is not decoration. Reporting a mean without the count of contributing observations hides how much data the statistic rests on, and a mean computed from five rows deserves different treatment than one from five thousand. Include n in every summary table by default.

For a simple worked example, suppose a column of ten incomes (in thousands) reads: 30, 35, 42, 42, 47, 51, 55, 61, 68, 89. The mean is 520 divided by 10, or 52.0; the median is the average of the fifth and sixth values, (47 + 51) / 2, or 49.0. Because the mean sits above the median, the distribution is pulled right by the higher values—information a reader needs, and something a well-built summary exposes naturally by reporting both statistics.

Summarize Categories and Build Grouped Tables

Categorical columns need counts, not averages. The tidyverse verb count() does this in one line:

The sort = TRUE argument ranks categories by frequency, which is usually what a reader wants to see first. To add proportions, extend the pipeline:

Grouped summaries combine both worlds. To compute average income per department while keeping the observation count:

The n() function counts rows per group, including rows where income is missing, while mean(income, na.rm = TRUE) excludes missing incomes. That mismatch is a common source of confusion: a group's n may exceed the number of incomes that fed its mean. If precision matters, add a second count such as sum(!is.na(income)) and label both columns clearly.

A compact table helps compare summary approaches at a glance:

Goal Function Output type Best for
Quick numeric profile summary() Printed text First look at a numeric column
Exportable numeric stats summarise() Data frame Reports and further processing
Category frequencies count() Data frame Character or factor columns
Cross-tabulation table() Named table Two categorical columns
Group means group_by() + summarise() Data frame Comparing groups

Each row answers a different question, so the mismatch in output types is intentional rather than a flaw—choose based on what you'll do with the result next.

Check Your Summary With a Simple Validation Block

A summary script that runs without errors can still be wrong. Add a short validation section at the end of the script that confirms the population being summarized:

The stopifnot() call halts the script if the data frame is empty, which catches a failed import before you waste time interpreting empty output. Comparing a hand-counted category size against count() output is the cleanest success check for categorical summaries: pick one category, count its rows with a targeted expression, and confirm the number matches your table.

For numeric summaries, cross-check the mean against the median and against the minimum and maximum. If the mean falls outside the range between minimum and maximum, something is broken—usually a character column coerced incorrectly or a filtering step that removed valid rows. These checks take seconds and catch the majority of silent errors.

Handle Common Failures and Know When to Stop

The most frequent failure is type mismatch: numeric-looking columns imported as text. The symptom is a summary() output that reports "Length" and "Class" instead of quartiles. The fix is converting with as.numeric() after removing separators, then re-running the summary. A second common issue is missing values quietly shrinking effective sample sizes; the symptom is an n column far below the row count, and the fix is deciding explicitly whether to filter or to report missingness as its own category.

A third failure is factor ordering. Category tables sorted alphabetically when you expected them sorted by magnitude usually mean a character column; converting with factor(dept, levels = ...) gives you control. If a grouped summary returns unexpected groups, check for trailing spaces or inconsistent capitalization in the category column—"Sales " and "Sales" count as different values unless you clean them with str_trim().

Stop and consult a data professional or your organization's data steward when the script requires joining tables whose keys you don't fully understand, when missingness patterns suggest the data collection itself was flawed, or when the summary will feed a regulatory, financial, or clinical decision. Those situations need documented lineage, not just working code. Ordinary exploratory summaries on your own tidy data rarely require escalation.

Why the Order of Operations Matters

The sequence in this guide—project setup, import, inspection, cleaning, summary, validation, export—is not arbitrary. Inspection before cleaning tells you what needs fixing; cleaning before summarizing prevents type errors from propagating; validation before export stops wrong numbers from reaching a report. Reordering the steps, such as summarizing before checking missingness, produces output that looks fine in the console but misstates the population.

This ordering also makes the script maintainable. When the data updates next month, you re-run the script unchanged and the validation block tells you whether the new file is shaped like the old one. A summary script built in this order becomes a reusable tool rather than a one-off transcript of console commands.