STATHARBOR ANALYTICS · INTRODUCTION TO STATISTICS · CHAPTER 23
Introduction to R Programming
R is a widely used language for statistical computing and graphics. This chapter introduces the basics of R programming, including data structures, importing data, and performing simple analyses. Readers already familiar with R may skip this chapter.
Getting Started
R can be installed from https://cran.r-project.org. Use an integrated development environment such as RStudio for convenience. Basic calculations can be performed at the console:
2 + 2
sqrt(3)
log(10)
Assign values to variables with the assignment operator
<- or =. Vectors are created using the
c() function.
Data Structures
Vectors: ordered collections of elements of the same type. Operations are vectorised:
c(1,2,3) + 1returns2 3 4.Matrices: two–dimensional arrays created with
matrix(). Uset()for transpose.Data frames: tables where each column can be a different type. Created with
data.frame()or by reading files. Rows are observations and columns are variables.Lists: containers that can hold elements of different types and lengths.
Access elements with square brackets: x[1] returns the
first element of vector x; df[ ,1] returns the
first column of a data frame.
Importing and Exploring Data
R reads data from various formats: CSV, Excel, SPSS, etc. For example, to read a CSV file:
df <- read.csv("data.csv")
head(df)
summary(df)
str(df)
These functions display the first few rows, summary statistics and the structure of the data frame.
Basic Plotting
R’s base plotting functions create quick visualisations. For example, plot a scatterplot and histogram:
plot(df$height, df$weight, xlab="Height", ylab="Weight", main="Height vs Weight")
hist(df$age, breaks=10, main="Histogram of Age", xlab="Age")
For more advanced graphics, the ggplot2 package provides
a grammar of graphics. Install with
install.packages("ggplot2") and then:
library(ggplot2)
ggplot(df, aes(x=height, y=weight)) + geom_point() + geom_smooth(method="lm")
Simple Linear Regression in R
Fit a linear model using lm() and summarise the
results:
lm_fit <- lm(weight ~ height, data=df)
summary(lm_fit)
plot(df$height, df$weight)
abline(lm_fit)
Exercises
Practice
Create a vector of numbers and compute its mean, median and standard deviation using built–in functions. Compare to manual calculation.
Read a CSV file (or simulate data) with at least three variables. Compute summary statistics and produce scatterplots and boxplots.
Write a function in R that takes a numeric vector and returns the sum of squared deviations from the mean. Test it on different inputs.
Use
ggplot2to create a scatterplot of two variables with a fitted regression line and 95% confidence band.
References
Matloff N. The Art of R Programming. No Starch Press; 2011.
Wickham H, Grolemund G. R for Data Science. O’Reilly; 2017.
Chambers JM. Programming with Data. Springer; 1998.