scientific-methodology
A Guide to Using R for Basic Statistical Analysis
Table of Contents
R is a powerful and versatile programming language that has become a cornerstone of modern statistical analysis and data science. Its open-source nature, extensive package ecosystem, and strong community support make it an ideal choice for beginners and professionals alike. Whether you are exploring data for academic research, business intelligence, or personal projects, R provides the tools you need to clean, analyze, and visualize data effectively. This expanded guide walks you through the essential steps of using R for basic statistical analysis, from setting up your environment to interpreting results and presenting them graphically.
Getting Started with R
Installing R and RStudio
To begin using R, the first step is to install the R language itself. Visit the official Comprehensive R Archive Network (CRAN) and download the appropriate version for your operating system. Follow the installation wizard to complete the setup. While R can be used from a basic command-line interface, most users prefer an integrated development environment (IDE) such as RStudio. RStudio provides a user-friendly workspace with a script editor, console, environment viewer, and plotting windows, making coding and debugging much easier.
Your First R Script
After installation, open RStudio and create a new R script (File > New File > R Script). You can type commands directly into the console or write them in the script and execute them. A simple starting point is to use R as a calculator:
2 + 3
sqrt(16)
log(100)
Press Ctrl+Enter (Windows) or Cmd+Return (Mac) to run a line. Output appears immediately in the console. This interactive workflow is fast and intuitive for learning.
Setting Up Your Working Directory
Before handling data files, set a working directory where R will look for and save files. Use setwd() or, in RStudio, go to Session > Set Working Directory > Choose Directory. This keeps your project organized and prevents file path errors.
Understanding R Data Types and Structures
R works with several fundamental data types: numeric, character (text), logical (TRUE/FALSE), and factors (categorical). Data structures include vectors, lists, matrices, and data frames. For statistical analysis, the data frame is the most commonly used structure, as it can hold multiple column types like a spreadsheet.
Creating a Vector
ages <- c(25, 30, 35, 40)
names <- c("Alice", "Bob", "Carol", "Dave")
Creating a Data Frame
data <- data.frame(
Name = c("Alice", "Bob", "Carol", "Dave"),
Age = c(25, 30, 35, 40),
Height = c(175, 180, 165, 170),
Smoker = c(TRUE, FALSE, FALSE, TRUE)
)
print(data)
You can inspect the structure using str(data) and view summary statistics with summary(data).
Importing Data into R
While manual data entry works for small datasets, real-world analysis requires importing data from external files. R supports many formats, with CSV being the most common.
Reading a CSV File
mydata <- read.csv("path/to/file.csv", header = TRUE)
Use header = TRUE if the first row contains column names. For Excel files, the readxl package provides read_excel(). For databases, the DBI package can connect to SQL databases.
Checking Imported Data
After importing, always inspect your data with head(mydata), tail(mydata), and nrow(mydata) to ensure it loaded correctly.
Data Wrangling with dplyr
The dplyr package (part of the tidyverse) offers a grammar of data manipulation that is intuitive and fast. Install and load it:
install.packages("dplyr")
library(dplyr)
Key Functions
- filter() – select rows based on conditions
- select() – pick columns by name
- mutate() – create new columns
- summarize() – calculate summary statistics
- group_by() – group data for grouped operations
Example Workflow
result <- mydata %>%
filter(Age > 30) %>%
group_by(Gender) %>%
summarize(
avg_height = mean(Height, na.rm = TRUE),
count = n()
)
print(result)
The pipe operator %>% chains operations together, making code readable.
Descriptive Statistics
Before conducting formal tests, explore and summarize your data. R provides built-in functions:
mean(),median(),sd(),var()– measures of central tendency and spread.min(),max(),quantile()– range and percentiles.summary()– quick overview of all variables.table()– frequency tables for categorical variables.
Example
summary(mydata$Age)
table(mydata$Gender)
sd(mydata$Income, na.rm = TRUE)
For grouped summaries, use dplyr::group_by() combined with summarize().
Basic Statistical Tests
Statistical tests help you make inferences about populations from sample data. R includes many tests out of the box.
One-Sample and Two-Sample t-Tests
The t.test() function performs both. For a one-sample test comparing the mean of a vector to a known value:
t.test(mydata$Age, mu = 35)
For an independent two-sample test comparing two groups:
t.test(mydata$Height ~ mydata$Gender)
Paired t-Test
Use paired = TRUE when measurements are on the same subjects (e.g., before and after treatment).
Chi-Square Test for Independence
The chisq.test() function works on contingency tables:
tbl <- table(mydata$Gender, mydata$Smoker)
chisq.test(tbl)
Interpret the p-value: a low p (< 0.05) suggests a relationship between variables, while a high p suggests independence.
Analysis of Variance (ANOVA)
Compare means across three or more groups using aov():
fit <- aov(Height ~ Treatment, data = mydata)
summary(fit)
If significant, perform post-hoc tests like TukeyHSD to see which groups differ.
Correlation and Regression
Correlation
Measure the strength and direction of a linear relationship between two numeric variables with cor():
cor(mydata$Age, mydata$Height, method = "pearson")
Use cor.test() to get a p-value and confidence interval:
cor.test(mydata$Age, mydata$Height)
Simple Linear Regression
The lm() function fits linear models. For a single predictor:
model <- lm(Height ~ Age, data = mydata)
summary(model)
The output shows coefficients, R-squared, and p-values. For multiple predictors:
model <- lm(Height ~ Age + Gender, data = mydata)
summary(model)
Use predict() to make predictions on new data.
Data Visualization
Graphical representation is key to understanding data patterns and communicating findings.
Base R Graphics
R’s built-in plotting functions are flexible:
plot(x, y)– scatterplothist(x)– histogramboxplot(y ~ x)– side-by-side boxplotsbarplot(table(x))– bar chart
Example
plot(mydata$Age, mydata$Height,
main = "Age vs Height",
xlab = "Age (years)",
ylab = "Height (cm)",
col = "blue", pch = 16)
Advanced Visualization with ggplot2
For publication-quality figures, the ggplot2 package (also in tidyverse) uses a layered grammar. Install and load:
install.packages("ggplot2")
library(ggplot2)
Basic ggplot2 Example
ggplot(mydata, aes(x = Age, y = Height)) +
geom_point(color = "darkgreen") +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Age vs Height with Linear Fit",
x = "Age (years)", y = "Height (cm)") +
theme_minimal()
You can customize themes, colors, and add facets for grouped plots. For more, see the ggplot2 documentation and the RStudio cheatsheets.
Conclusion
R offers a complete environment for basic statistical analysis, from data import and cleaning to powerful tests and stunning visualizations. By mastering the fundamentals covered in this guide – installing and setting up R, working with data frames, performing descriptive statistics and common hypothesis tests, building regression models, and creating informative plots – you have laid a strong foundation for more advanced analytics. Continue exploring R’s vast ecosystem of packages such as tidyr, readr, caret, and shiny to expand your capabilities. With consistent practice, you will find R an indispensable tool for turning data into insights.
For further learning, check out the official CRAN website for documentation and the Tidyverse website for modern data science workflows.