Book contents

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

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

  1. Create a vector of numbers and compute its mean, median and standard deviation using built–in functions. Compare to manual calculation.

  2. Read a CSV file (or simulate data) with at least three variables. Compute summary statistics and produce scatterplots and boxplots.

  3. 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.

  4. Use ggplot2 to create a scatterplot of two variables with a fitted regression line and 95% confidence band.

References