How to Use R for Statistical Analysis in Research
Introduction
If you have ever tried to reproduce a statistical analysis you ran six months ago, you understand the case for R. SPSS lets you click through menus and produces results that vanish the moment you close the window; R, by contrast, records every step in a script you can rerun, share, and audit. That single property — reproducibility — is why R has become the default tool in statistics departments, in public-health research, and in journals that now require open code alongside accepted manuscripts. Learning R for statistical analysis is one of the highest-leverage skills a researcher can acquire.
R is free, open-source, and runs on Windows, macOS, and Linux. It is maintained by the Comprehensive R Archive Network (CRAN), which hosts more than 20,000 user-contributed packages covering everything from Bayesian regression to text mining. The companion IDE, RStudio, turns R from a command-line calculator into a fully featured analysis environment with a script editor, console, plot pane, and environment browser. Together, R and RStudio are now installed on most university research machines.
This guide walks you through a complete R workflow, from installation through reporting, with a focus on the practical commands a Master’s or PhD scholar actually needs. If you would rather delegate the coding, our data analysis service includes R-fluent statisticians who write the script, run the analysis, and deliver an annotated report. For the broader context, see our SPSS guide (the leading commercial alternative) and our data analysis chapter template. Mastering R for statistical analysis pays dividends across an entire research career, not just one thesis.
Installing R and RStudio
Install in two steps. First, download base R from cran.r-project.org and run the installer for your operating system. Second, download RStudio Desktop (the free version) from posit.co. RStudio is an IDE that sits on top of base R; it does not install R itself. Once both are installed, open RStudio — never base R — and you should see four panes: Script (top-left), Console (bottom-left), Environment (top-right), and Files/Plots/Help (bottom-right).
Set up a project for each analysis: File → New Project → New Directory → New Project. This creates a folder with a .Rproj file that remembers your working directory, history, and settings. Always work inside a project; never scatter scripts across your desktop. Install the core packages you will need on day one:
install.packages(c("tidyverse", "haven", "psych", "car", "ggplot2", "rstatix", "gtsummary", "apaTables"))
Load the ones you need at the top of every script with library(). Never call install.packages() inside an analysis script — it re-downloads packages every time you run the file.
The tidyverse is a collection of R packages (dplyr, tidyr, ggplot2, readr, purrr) that share a consistent grammar. It is far more readable than base R and is now the dominant style in academic data science. Learn tidyverse first; pick up base R as needed.
Importing Data into R
R reads almost any data format, but the path differs by source. The haven package is your bridge to commercial software:
library(haven)
library(readr)
# From SPSS .sav
data <- read_sav("survey.sav")
# From Stata .dta
data <- read_dta("survey.dta")
# From Excel .xlsx
library(readxl)
data <- read_excel("survey.xlsx")
# From CSV
data <- read_csv("survey.csv")
After import, inspect the dataset with three commands: str(data) shows the structure and variable types; summary(data) gives basic descriptives; head(data) prints the first six rows. Convert categorical variables stored as numbers into factors with as.factor() — otherwise R will treat them as continuous in regression models, producing nonsense output.
Cleaning and Wrangling with dplyr
Real datasets arrive messy. The dplyr package (part of tidyverse) provides five verbs that handle 90% of wrangling: filter() (select rows), select() (select columns), mutate() (create new variables), summarise() (aggregate), and group_by() (split-apply-combine). They are chained with the pipe operator %>% (or the native |> in R 4.1+).
library(dplyr)
cleaned <- data %>%
filter(age >= 18, !is.na(gender)) %>%
mutate(age_group = cut(age, breaks = c(18, 30, 45, 60, 100),
labels = c("18-29", "30-44", "45-59", "60+"))) %>%
select(id, age, age_group, gender, score) %>%
group_by(age_group, gender) %>%
summarise(mean_score = mean(score, na.rm = TRUE),
sd_score = sd(score, na.rm = TRUE),
n = n())
That single block filters out minors and missing gender, recodes age into groups, selects the columns you need, and produces a grouped summary table — the equivalent of an hour of menu-clicking in SPSS. The rstatix package builds on dplyr to pipe results directly into t-tests, ANOVA, and correlation in a tidy format.
Read x %>% f() as “take x, then apply f.” Pipes make multi-step transformations readable in left-to-right order, mirroring how you think about the analysis. Avoid nested function calls like summarise(filter(select(data, ...), ...), ...) — they are correct but illegible.
Descriptive Statistics and Visualisation
For descriptives, use psych::describe() or summary(). For grouped descriptives, combine group_by() with summarise() as shown above. The gtsummary package produces publication-ready summary tables in one line:
library(gtsummary)
data %>% tbl_summary(by = group,
statistic = list(all_continuous() ~ "{mean} ({sd})",
all_categorical() ~ "{n} / {N} ({p}%)"))
For visualisation, ggplot2 implements the grammar of graphics — a layered system where you declare the data, the aesthetic mapping (which variables go on which axes), and the geometric object (point, bar, line, boxplot). A boxplot of score by group, with individual points overlaid:
library(ggplot2)
ggplot(data, aes(x = group, y = score, fill = group)) +
geom_boxplot(alpha = 0.6) +
geom_jitter(width = 0.15, alpha = 0.5) +
stat_summary(fun = mean, geom = "point", shape = 23, size = 3, fill = "white") +
theme_minimal() +
labs(title = "Score by Group", x = "Group", y = "Score")
A good plot communicates more than a table, and reviewers increasingly expect to see distributions, not just summary statistics. For a deeper introduction to grammar-of-graphics thinking, the standard reference is Wickham’s ggplot2: Elegant Graphics for Data Analysis.
Running the Core Statistical Tests
R’s base distribution includes every common inferential test. The tidy rstatix wrappers return results as data frames you can pipe into further analysis or report tables:
- Independent t-test:
t.test(score ~ group, data = data, var.equal = TRUE) - Paired t-test:
t.test(pre, post, paired = TRUE) - One-way ANOVA:
aov(score ~ group, data = data) %>% summary()— follow withTukeyHSD()for post-hoc comparisons - Mann-Whitney U:
wilcox.test(score ~ group, data = data) - Kruskal-Wallis:
kruskal.test(score ~ group, data = data) - Chi-square:
chisq.test(data$group, data$outcome) - Pearson correlation:
cor.test(data$x, data$y, method = "pearson") - Linear regression:
lm(y ~ x1 + x2, data = data) %>% summary() - Logistic regression:
glm(outcome ~ x1 + x2, data = data, family = binomial) %>% summary()
Check assumptions with the car and lmtest packages: shapiro.test() for normality, leveneTest() for homogeneity of variance, dwtest() for autocorrelation in regression. The performance package produces a one-shot diagnostic report for any regression model. For a fuller decision tree on which test to use, see our statistical tests guide.
With n = 5,000, even trivial differences produce p < 0.001. Always report effect sizes (Cohen’s d, eta-squared, R²) and confidence intervals. The effectsize package computes them in one line: effectsize::cohens_d(score ~ group, data = data).
Reproducible Reports with R Markdown
R is the only major statistics package where every step of the analysis — data import, transformation, testing, plotting — lives in a script you can rerun years later. That is what makes R for statistical analysis the standard for reproducible research.
The real power of R emerges when you combine code, output, and prose in a single reproducible document using R Markdown. An .Rmd file contains narrative text (in Markdown), embedded R code chunks (in fenced blocks), and YAML metadata that controls output format — Word, PDF, HTML, or PowerPoint. Knit the file with the knitr package and R executes every chunk, weaves in the results, and produces a finished report.
The payoff is enormous. When reviewers ask for an additional analysis, you add a code chunk, re-knit, and the entire report regenerates — tables, figures, p-values, and prose all update consistently. No more copy-pasting SPSS output into Word and hoping you remembered to update every number. Many journals now accept .Rmd or .qmd (Quarto) submissions directly, and platforms like OSF let you publish the underlying script alongside the paper.
A minimal R Markdown skeleton:
---
title: "Survey Analysis"
author: "Your Name"
date: "`r Sys.Date()`"
output: word_document
---
## Results
The mean score in the treatment group was `r mean(treatment$scores)`
(SD = `r sd(treatment$scores)`).
```{r}
t.test(score ~ group, data = df)
```
Write your thesis results chapter as an R Markdown document. Every number in the prose is computed live from the data, so it can never drift out of sync. When you defend, you can rerun the entire chapter in front of the examiner to prove reproducibility.
Managing the Learning Curve
R has a steeper learning curve than SPSS, and the first two weeks will feel slow. Three habits flatten the curve:
- Comment every script. Future-you is the most important reader. A comment per line of non-obvious code is not excessive.
- Use cheat sheets. RStudio ships with one-page cheat sheets for dplyr, ggplot2, and R Markdown under Help → Cheatsheets. Print them; pin them above your desk.
- Ask R for help.
?t.testopens the documentation for any function;example(lm)runs a worked example. Stack Overflow has answers to virtually every error message R can produce.
Within a month, you will write in R faster than you can click through SPSS. Within a semester, you will be running analyses SPSS cannot do — mixed-effects models, Bayesian regression, survival analysis, network analysis — and producing reports that examiners and reviewers respect for their transparency.
Conclusion
R for statistical analysis rewards the upfront investment many times over. Install R and RStudio, work inside projects, learn the tidyverse verbs, run your tests with documented assumption checks, and write your results chapter in R Markdown so every number is reproducible. The result is not just better analysis — it is a research workflow that scales from your first Master’s project to your hundredth journal article. If you want an expert to set up the analysis pipeline or train your team, our data analysis support covers R scripting, visualisation, and reproducible reports. Pair this guide with our SPSS walkthrough, survey design best practices, and sampling methods overview, and reach out through our contact page for a free consult.
Frequently Asked Questions
R has a steeper initial learning curve because it requires code rather than point-and-click menus. However, after two to four weeks of practice, most researchers find R faster and more flexible than SPSS, especially for reproducible analysis.
Yes. R is open-source under the GNU GPL licence and free for any use, including commercial. RStudio Desktop is also free. You can install both on any number of machines without licensing concerns.
Yes. The haven package reads .sav, .dta, and .sas7bdat files directly into R as tidy tibbles, preserving value labels and missing-data codes. Most researchers migrating from SPSS find the transition straightforward.
You need basic scripting literacy — loading packages, calling functions, piping commands — but not full software-engineering skills. The tidyverse syntax is designed for data analysts, not programmers, and most graduate students reach competence in one semester.
Install tidyverse (data wrangling and plotting), haven (importing SPSS/Stata files), psych (descriptive statistics), car (regression diagnostics), rstatix (tidy statistical tests), gtsummary (publication tables), and effectsize (effect-size computation). These cover 95% of graduate research needs.
Need Help With Your Research?
Our team of PhD-qualified subject specialists is ready to assist. Get a free consultation and custom quote within 2 hours.