Graphics. Summarising data. More syntax. Looping. Reshaping data.
This worksheet is based on the eleventh lecture of the Statistical Modelling in Stata course, created by Dr Mark Lunt and offered by the Centre for Epidemiology Versus Arthritis at the University of Manchester. The original Stata exercises and solutions are here translated into their R equivalents.
Refer to the original slides and Stata worksheets here.
Load the dataset uselifeexp
from the Stata web site.
It concerns life expectancy in various subgroups in the United States from 1900–2000.
uslifeexp <- foreign::read.dta('https://www.stata-press.com/data/r8/uslifeexp.dta')
Similar datasets are available within R, but we load the Stata one for ease of comparison with the original worksheet.
Produce a simple scatter plot of life expectancy against year.
plot(le ~ year, data = uslifeexp) # or plot(uslifeexp$year, uslifeexp$le)
You should see life expectancy increasing steadily, with a blip of very low life expectancy in 1918.
Now we will add a title to this graph.
Go back to your script and add a main
argument to the plot
command.
We can also change the y-axis label, ylab
.
plot(le ~ year, data = uslifeexp,
ylab = 'life expectancy',
main = 'US Life Expectancy')
Now we are going to extend the y-axis back to 0, rather than starting at 40.
This is set by passing a vector of length 2 to the ylim
argument.
Now we will practise overlaying graphs, using the same dataset.
We can compare male and female life expectancy.
First plot the points for male life expectancy, then add the female points to the same plot using the points
function.
Set the plotting characters to different symbols and colours using pch
and col
arguments.
Use the following guide:
Add a legend, if you like.
You should see that life-expectancy is increasing over time in both sexes, but consistently higher in females.
Add regression lines to the plot, after fitting the appropriate linear models, using the abline()
function.
You may wish to adjust your ylim
.
You can add confidence intervals to the plot in the same way, but it’s a bit of a pain.
A better option is ggplot2, which fits models, adds legends and shades the confidence intervals automatically. However, the package demands data in a long format, so that we can treat sex as a factor, rather than as two separate variables. Reshaping data will be explained later, but here’s a preview.
library(tidyverse)
uslifeexp %>%
select(year, le_female, le_male) %>%
pivot_longer(le_female:le_male,
names_to = 'sex',
values_to = 'lifeexp') %>%
mutate(sex = str_remove(sex, 'le_')) %>% # clean up the labels
ggplot() + aes(year, lifeexp, colour = sex) +
geom_smooth(method = lm, formula = y ~ x) +
geom_point() +
labs(y = 'life expectancy', title = 'US Life Expectancy') +
theme_classic() # Just because I don't like the default grey theme
Read the cancer
dataset into R.
cancer <- foreign::read.dta('http://www.stata-press.com/data/r9/cancer.dta')
Find out what the dataset is about with str
.
str(cancer)
(These attr
ibutes are carried over from Stata.)
nrow(cancer)
summary()
function to get some idea of the values taken by the different variables. What was the longest followup time?summary(cancer)
See summary output above, or use
max(cancer$studytime)
When first imported via read.dta
this becomes an integer vector, so the summary above for drug
might not make much sense.
If you don’t want to convert this variable to a factor, then you can use
unique(cancer$drug)
otherwise, convert to factor and summarise again.
You can also now use
nlevels(cancer$drug)
See summary output above, or use
range(cancer$age)
See summary output above, or use
mean(cancer$age)
We don’t get standard deviations in summary output, so use:
sd(cancer$studytime)
table
(or xtabs
) to cross-tabulate the number and percentage of subjects who died on each treatment. How many subjects on placebo died?19 subjects died on placebo (= drug 1).
with(cancer, proportions(table(drug, died), margin = 1))
43% of subjects on treatment 2 died.
Other methods include
Many different ways of doing it, as above.
agegrp
, dividing subjects into two more-or-less equally sized groups.You can try using cut(age, 2)
but this will split the data at 57 into equal lengths of years, rather than numbers of subjects.
You need to specify the median manually, and then either set lower and upper bounds (c(min(age), median(age), max(age))
or equivalently quantile(age, c(0, .5, 1))
).
Or use findInterval
, which lets you specify a single breakpoint (but doesn’t label the result).
# Generates a vector of 0s and 1s:
cancer$agegrp <- findInterval(cancer$age, median(cancer$age))
# Slightly better as you get labels:
cancer$agegrp <- cut(cancer$age,
quantile(cancer$age, c(0, .5, 1)),
include.lowest = TRUE)
If you prefer a specific pre-made function, use cut2
from the Hmisc package, which will cut into the number of quantile groups specified by argument g
.
cancer$agegrp <- Hmisc::cut2(cancer$age, g = 2)
Lots of ways of doing this.
Or in data.table:
library(data.table)
setDT(cancer)
cancer[, group_size := .N, by = agegrp]
All give the same result.
Assign the dataset to the symbol mycancer
, for later exercises.
mycancer <- cancer
Warning.
You will rarely need to use loops of any kind in R.
Nearly all tasks are better accomplished by using vectorised operations or using an apply (or map) type function.
Exceptions to this are iterative processes that are performed for their side effects, such as saving to file, producing plots or printing to the console.
(However, even these might be accomplished with functional programming verbs like purrr::walk
.)
Nevertheless, here’s a direct R transliteration of the Stata worksheet.
For a simple illustration of looping, type
Note.
You don’t need to wrap the loop expression in curly brackets {}
unless it spans multiple lines.
Here it’s just a single print
operation, so they are omitted.
You should still have the dataset mycancer
from the last section.
You can now enter the following code:
This should produce two cross-tabulations, one for drug
against died
, and the other for agegrp
against died
.
Note. Expressions inside loops need an explicit call to print()
to appear in the console.
For a more complex example of using for()
, load the life-expectancy data (uslifeexp
) from earlier.
We will create graphs for all of the variables:
In interactive use, you can subset a data frame using df$myvar
, but if you want to select a column by a string then you need df[[x]]
, which will give the same result as if you’d typed the value of x after the dollar sign.
This is so you don’t mix up a column whose name is equal to the value of x
with a column whose name is literally “x”.
If you really did want to produce a set of plots like above, you might be better off using lattice or ggplot2 to produce a set of small multiples (facets); this is demonstrated at the bottom of the page. A prerequisite is reshaping the data from wide to long, which is described in the next section.
There are several ways to reshape data in R.
melt
and cast
functions (also built into data.table)pivot_longer
and pivot_wider
functions (formerly known as gather
and spread
)The main differences between these three approaches are that reshape
tries to do everything in a single function, reshape2 uses a set of functions to coerce the data to and from an intermediate (molten) format, and tidyr has a pair of functions that convert between wide and long directly.
Generally speaking, you want to use either reshape2 or tidyr, and if in doubt then start with tidyr and see how you get on.
Read the bplong
dataset into R with
bplong <- foreign::read.dta('https://www.stata-press.com/data/r8/bplong.dta')
Use an appropriate method to get the mean and standard deviation of the blood pressure for categories when = 'Before'
and when = 'After'
, separately.
Make a note of these so you can check later that your reshaping was successful.
To reshape these data into wide form, the unique identifier is patient
and the variable to ‘widen’ is when
.
First let’s see reshape:
bpwide <- reshape(bplong,
v.names = 'bp',
timevar = 'when',
idvar = 'patient',
direction = 'wide')
With reshape2, you can melt
an object into a ‘molten’ long-format data frame, then cast
it back into the desired wider format.
And finally the package tidyr provides pivot_wider
, which performs the reshape operation in a single function call (the dual function is pivot_longer
) without having to melt it first.
library(tidyr)
bpwide <- bplong %>% pivot_wider(names_from = 'when', values_from = 'bp')
Check the summary statistics have not changed.
bpwide %>%
summarise_at(vars(Before:After),
list(mean = mean, sd = sd))
Reshaping from wide to long is especially useful for packages like ggplot2, as it allows you to colour or facet according to different variables. It’s also handy when summarising lots of variables at once.
Reload the uslifeexp
life expectancy data from earlier.
There are a series of variables giving the life-expectancy in different subgroups of the US population over the years, and a variable le
containing the overall life-expectancy.
We will change this to have several observations for each year, a single variable le
containing the life expectancy and a variable
group saying which subgroup the life-expectancy applies to.
First, we need to change the name of the variable le
to le_total
, so that there is something to put in the group
variable for the overall life expectancy.
colnames(uslifeexp)[2] <- 'le_total'
Now, unique observations are identified by the variable year
, the variable we want to have in the long data is le
, and the variable we want to identify which variable in wide form corresponds to an observation in long form is called group
.
The different ways of achieving this are as follows.
Firstly, for the masochists, reshape
.
Next a reshape2 workflow.
It’s a single melt
operation; no need to cast
afterwards because a long format is what we want.
life_long <- melt(uslifeexp,
id.vars = 'year',
variable.name = 'group',
value.name = 'le')
And the equivalent syntax using tidyr.
Here we use the selector syntax “-year
” to mean ‘pivot all of the columns except this one’.
You could also use starts_with('le')
to select the columns by name.
life_long <- uslifeexp %>%
pivot_longer(-year, names_to = 'group', values_to = 'le')
Hence you can recreate the scatter plot from earlier.
life_long %>%
filter(group %in% c('le_male', 'le_female')) %>%
mutate(group = str_remove(group, '^le_')) %>% # remove prefix
ggplot() + aes(year, le, colour = group) +
geom_smooth(method = lm) +
geom_point() +
labs(colour = 'sex', y = 'life expectancy',
title = 'US Life Expectancy')
Better yet, let’s plot all of the variables at once. No loops necessary!
ggplot(life_long) +
aes(year, le) +
geom_point() +
facet_wrap( ~ group)
Other packages are available, of course. Another option for small-multiples plots is lattice.