4Lab: Correlation and Multiple Linear Regression with Qualitative Variables
Author
Zi Ye
Published
November 1, 2026
Open this lab in RStudio: in the Files pane, click labs and then 03.QualitativeVariable.qmd. Save your own copy in myLabs (File -> Save As...) and work on the copy. Work through it from top to bottom, running each code chunk and adding your notes and answers in the file. (First time? See the Setup: RStudio on a PC or Laptop if you’re working on your own laptop)
The lecture’s slides can be found on Canvas Week 3 here.
Last week, we introduced Multiple Linear Regression (MLR) - a statistical method that models the relationship between a dependent variable and two or more independent variables, allowing researchers to examine how various predictors jointly influence an outcome. By using the following R code, we create and interpret the model:
model <- lm(pct_Very_bad_health ~ pct_No_qualifications + pct_Males + pct_Higher_manager_prof, data = census)
summary(model)
In a regression model, independent/predictor variables could be continuous or categorical (or qualitative). While continuous variables capture quantitative effects, categorical variables provide insights into differences across groups. When we say categorical variables, we normally mean:
Nominal Data: categorical data without natural order. E.g. Gender, Colour, Country…
Ordinal Data: categorical data with a meaningful order. E.g. Education level, Customer satisfaction, Grade…
By blending continuous and categorical predictors, MLR with categorical variables enhances the model’s ability to reflect real-world complexities and improves interpretability, as it allows analysts to assess how each category or group within an independent variable influences the dependent variable.
For most categorical (especially the nominal) variables, they cannot be included in the regression model directly as a continuous independent variable. Instead, these qualitative independent variables should be included in regression models by using the dummy variable approach, transforming categorical information into a numerical format suitable for regression analysis.
However, R provides a powerful shortcut, by automatically handling this process when the categorical variable is designated as a factor and included in the regression model. This makes it much easier for you to use categorical variables in the regression model to assess the effects of categorical groupings on the dependent variable alongside continuous predictors.
Learning Objectives:
In this week’s practical we are going to
Analyse categorical/qualitative variables
Estimate and interpret a multiple linear regression model with categorical variables
Make predictions using a regression model
4.1 Analysing categorical variables
Recall that in Week 2 you became familiar with R by using the Census data. Today we will explore both the Family Resource Survey (FRS) and the Census data by using their categorical variables. The Census data is already in your ‘data/Census2021/’ folder, and you uploaded ‘FRS16-17_labels.csv’ to ‘data/FRS/’ in Week 1. If it is not there, download it from Canvasand upload it to ‘data/FRS/’ (use the Upload button in the Files pane: see Setup, section 6). From the same Canvas page, also download ‘FRS_dictionary.xlsx’ to your computer: it explains what each variable means.
To start today’s practical session, we first will use ‘FRS16-17_labels.csv’. You can open the .csv file in Excel and see that, unlike the Census dataset, the FRS dataset contains many qualitative/categorical variables, such as hh_tenure (Housing Tenure), happy (How happy did you feel yesterday?), health (How is your health in general), etc. To know the meaning of all the column names and the values in cell, you may need to refer to the ‘FRS_dictionary.xlsx’ to help your understanding. Recall from our lecture that these categorical variables will need to be treated as dummy variables in the regression model. In R, the variable type of qualitative/categorical variables is called ‘factor’.
As usual we first load the necessary libraries.
If R returns a “cannot open file” error, check in the Files pane that the file is really in the folder named in the code (e.g. data/FRS/).
Libraries used today:
dplyr: a basic library provides a suite of functions for data manipulation
ggplot2: a widely-used data visualisation library to help you create nice plots through layered plotting.
tidyverse: a collection of R packages designed for data science, offering a cohesive framework for data manipulation, visualization, and analysis. Containing dplyr, ggplot2 and other basic libraries.
broom: a part of the tidyverse and is designed to convert statistical analysis results into tidy data frames.
forcats: designed to work with factors, which are used to represent categorical data. It simplifies the process of creating, modifying, and ordering factors.
vcd: visualise and analyse categorical data.
A useful shortcut to format your code: select all your code lines, use Ctrl+Shift+A to automatically format them in a tidy way.
4.1.1 Data overview
All these packages are already installed in your codespace, so we just load them:
# Load necessary librarieslibrary(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library(ggplot2)library(broom)
Or we can use library tidyverse which includes ggplot2, dplyr and other fundamental libraries together already.
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ forcats 1.0.0 ✔ stringr 1.5.2
✔ lubridate 1.9.4 ✔ tibble 3.3.0
✔ purrr 1.1.0 ✔ tidyr 1.3.1
✔ readr 2.1.5
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
We will also use the forcats library, so
library(forcats)
Exactly as you did in previous weeks, we first load in the dataset:
Recall that in previous weeks we used the following code to get an overview of the dataset. Familiarise yourself with it again:
View(frs_data)
and also summary() to produce summaries of each variable
summary(frs_data)
You may notice that for the numeric variables such as hh_income_gross (household gross income) and work_hours (worked hours per week), the summary() offers useful descriptive statistics. While for the qualitative information, such as age_group (age group), highest_qual (Highest educational qualification), marital_status (Marital status) and nssec (Socio-economic status), the summary() function is not as useful, since reporting a mean or median makes little sense for categories.
When performing descriptive analysis for categorical or qualitative variables, we focus on summarising the frequency and distribution of categories within the variable. This analysis helps understand the composition and diversity of categories in the data, which is especially useful for identifying patterns, common categories, or potential data imbalances.
Dependent child
10299
Full-time student
963
Higher professional occupations
3004
Intermediate occupations
4372
Large employers and higher managers
1025
Lower managerial and professional occupations
8129
Lower supervisory and technical occupations
2400
Never worked or long-term unemployed
1516
Not classifiable
107
Routine occupations
4205
Semi-routine occupations
5226
Small employers and own account workers
2899
By using ggplot2, it is easy to create some nice descriptive charts for the categorical variables, just like you did for the continuous variables last week.
ggplot(frs_data, aes(x = highest_qual)) +geom_bar(fill="brown",width=0.5) +labs(title ="Histogram of Highest Qualification in FRS", x ="Highest Qualification", y ="Count")+#set text infotheme_classic()#choose theme type, try theme_bw(), theme_minimal() see differences
ggplot(frs_data, aes(x = health)) +geom_bar(fill="skyblue") +geom_text(stat ="count", aes(label = ..count..),vjust =-0.3,colour ="grey")+#add textlabs(title ="Histogram of Health in FRS", x ="Health", y ="Count")+#set text infotheme_minimal()
ggplot(frs_data, aes(x = nssec)) +geom_bar(fill ="yellow4") +labs(title ="Histogram of NSSEC in FRS", x ="NSSEC", y ="Count") +coord_flip()+#Flip the Axes, add a # in front of this line, to make the code in gray and you will see why we would better flip the axes at heretheme_bw()
If we want to reorder the Y axis by from highest to lowest, we use the functions in forcats library. fct_infreq(): orders by the value’s frequency of the variable nssec. fct_rev(): reverses the order to go from highest to lowest.
ggplot(frs_data, aes(x =fct_rev(fct_infreq(nssec)))) +geom_bar(fill ="yellow4") +labs(title ="Histogram of NSSEC in FRS", x ="NSSEC", y ="Count") +coord_flip()+#Flip the Axes, add a # in front of this line, to make the code in gray and you will see why we would better flip the axes at heretheme_bw()
You can change the variables in ggplot() to make your own histogram chart for the variables you are interested in. You will learn more of visualisation methods in Week 5’s practical.
4.1.2 Correlation
As before, rather than relying upon an impressionistic view of the strength of the association between two variables, we can measure that association by calculating the relevant correlation coefficients.
To calculate the correlation between categorical data, we first use Chi-squared test to assess the independence between pairs of categorical variables, then we use Cramér’s V to measure the strength of association - the correlation coefficient in R.
Pearson’s chi-squared test (χ2) is a statistical test applied to sets of categorical data to evaluate how likely it is that any observed difference between the sets arose by chance. If the p-value is low (typically < 0.05), it suggests a significant association between the two variables.
chisq.test(frs_data$health,frs_data$happy)
Warning in chisq.test(frs_data$health, frs_data$happy): Chi-squared
approximation may be incorrect
Pearson's Chi-squared test
data: frs_data$health and frs_data$happy
X-squared = 45594, df = 60, p-value < 2.2e-16
If you see a warning message of Chi-squared approximation may be incorrect. This is because some expected frequencies in one or more cells of the cross-tabulation (health * happy) are too low. The df means degrees of freedom and it is related to the size of the table and the number of categories in each variable. The most important message from the output is the estimated p-value, which shows as p-value < 2.2e-16 (2.2 with the decimal point moved 16 places to the left; it is a very small number, so it is written in scientific notation). P-value of the chi-squared test is far smaller than 0.05, so we can say the correlation is statistically significant.
Cramér’s V is a measure of association for categorical (nominal or ordinal) data. It ranges from 0 (no association) to 1 (strong association). The main downside of using Cramer’s V is that no information is provided on whether the correlation is positive or negative. This is not a problem if the variable pair includes a nominal variable but represents an information loss if both variables being correlated are ordinal.
# Load the 'vcd' packagelibrary(vcd)
Warning: package 'vcd' was built under R version 4.5.1
Loading required package: grid
# create the crosstable crosstab <-table(frs_data$health, frs_data$happy)# Calculate Cramér's V assocstats(crosstab)
X^2 df P(> X^2)
Likelihood Ratio 54036 60 0
Pearson 45594 60 0
Phi-Coefficient : NA
Contingency Coeff.: 0.713
Cramer's V : 0.454
#you can also directly calculate the association between variablesassocstats(table(frs_data$health, frs_data$age_group))
X^2 df P(> X^2)
Likelihood Ratio 26557 75 0
Pearson 23854 75 0
Phi-Coefficient : NA
Contingency Coeff.: 0.592
Cramer's V : 0.329
Q1: What are strongest and weakest associations health status?
Which of our selected person-level variables is most strongly/weakly correlated with an individual’s health status? Use the codes of Chi-square test and Cramer’s V to answer this question by completing Table 1.
Table 1 Person-level correlations with health status
Covariates
Correlation Coefficient
Statistical Significance
Cramer’s V
p-value
health
age_group
health
highest_qual
health
marital_status
health
nssec
4.2 Income inequality with respect to gender and health status
In this section, we will work with individual-level data (“FRS16-17_label.csv”) to explore income inequality with respect to gender and health status.
To explore income inequality, we need to work with a data set excluding dependent children. In addition, we look at individuals who are the representative persons of households. Therefore, we will select cases (or samples) that meet both conditions.
We want R to select persons only if they are the representative persons of households and they are not dependent children. The variables involved are hrp and dependent; using the categories “HRP” and “Independent”, you can select the appropriate cases. We also want to exclude the health variable reported as “Not known”.
frs_df <- frs_data %>%filter(hrp =="HRP"& dependent =="Independent"& health !="Not known")
Then, we create a new numeric variable Net_inc_pp indicating net income per capita, which is our dependent variable:
Min. 1st Qu. Median Mean 3rd Qu. Max.
-238160 9074 13347 15834 19136 864812
The distribution of the net household income per capita can be visualised by using ggplot()
ggplot(frs_df, aes(x = Net_inc_pp)) +geom_histogram(bins =250, #A higher bins value means more, narrower bars, covers smaller range of valuecolor ="black",fill ="skyblue",alpha =0.7 ) +labs(title ="Distribution of Net_inc_pp", x ="Value", y ="Frequency") +scale_x_continuous(labels = scales::label_comma()) +# Prevent scientific notation on the x axistheme_minimal()
The histogram shows that Net_inc_pp is highly right-skewed. Most households are concentrated in a narrow band between roughly £0 and £40,000 per person, with the peak around £10,000–£15,000, while a long tail stretches to the right up to a maximum of £864,812. This skewness is also visible in the summary() output: the mean (£15,834) is noticeably higher than the median (£13,347), because a small number of very high incomes pull the mean upwards. For skewed data like this, the median is a better measure of a “typical” value. There are also a few negative values (down to −£238,160), which can occur when households report losses, for example from self-employment. These extreme values are rare, but they stretch the x-axis so much that the main body of the distribution looks very thin. Keep them in mind when interpreting the regression results, as outliers can influence the estimated coefficients.
Now that we understand how net income per capita is distributed, we can ask why it varies so much between households. In this section, we explore whether income differs by gender and health status. If men and women, or people in better and worse health, have systematically different incomes, this would point to income inequality between these groups. Since both are categorical variables, we first need to check their categories before including them in a regression model.
Our two qualitative independent variables “sex” and “health”. Let’s first know what they look like:
table(frs_df$sex)
Female Male
7647 9180
table(frs_df$health)
Bad Fair Good Very Bad Very Good
1472 4253 6277 426 4399
Remember from the lecture what we did with Region in the long-term illness example before adding it to the regression model? Two steps are needed before including a categorical variable in a regression model:
Convert it to a factor, so that R treats it as categorical rather than as text or numbers.
Choose the reference category (baseline), as the model’s coefficients will show how each of the other categories differs from it.
Here, we use Female and Very Bad health as the reference categories, but you can choose others if you wish. The code below combines both steps in one line: as.factor() converts the variable to a factor, and fct_relevel() sets the reference category.
Implement the regression model with the two qualitative independent variables.
model_frs <-lm(Net_inc_pp ~ sex + health, data = frs_df) summary(model_frs)
Call:
lm(formula = Net_inc_pp ~ sex + health, data = frs_df)
Residuals:
Min 1Q Median 3Q Max
-255133 -6547 -2213 3515 845673
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 12115.5 762.9 15.881 < 2e-16 ***
sexMale 2091.2 240.6 8.691 < 2e-16 ***
healthBad -102.8 854.3 -0.120 0.904205
healthFair 1051.3 789.0 1.332 0.182751
healthGood 2766.0 777.4 3.558 0.000375 ***
healthVery Good 4931.8 787.8 6.260 3.95e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 15530 on 16821 degrees of freedom
Multiple R-squared: 0.01646, Adjusted R-squared: 0.01616
F-statistic: 56.29 on 5 and 16821 DF, p-value: < 2.2e-16
As in Week 2, here is what the code does:
lm() Function:
lm() stands for “linear model” and is used to fit a linear regression model in R.
The formula syntax Net_inc_pp ~ sex + health specifies a relationship between:
Dependent Variable: Net_inc_pp.
Independent Variables: sex and health. The model is fitted using the frs_df dataset (data = frs_df).
Storing the Model: The model_frs <- syntax stores the fitted model in an object called model_frs.
summary(model_frs) provides a detailed output of the model’s results, including:
Coefficients: Estimates of how each category differs from its reference category in Net_inc_pp (i.e., how each independent variable is associated with Net_inc_pp).
Standard Errors: How precise each coefficient estimate is (smaller = more precise).
t-values and p-values: Indicate the statistical significance of the effect of each independent (explanatory) variable.
R-squared and Adjusted R-squared: Show how well the independent variables explain the variance in the dependent variable.
F-statistic: Tests the overall significance of the model.
What conclusions could be drawn in terms of income inequalities with respect to gender and health status? Also think about the statistical significance of these differences.
The interpretation of this table is again similar to what you have learnt in Week 2, but you may find that R has automatically treated the categorical/qualitative variables sex and health as dummy variables. Each category gets a coefficient except the reference category set by fct_relevel(). That is why the output has sexMale but no sexFemale, and no healthVery Bad.
Each coefficient is therefore interpreted as a difference from the reference category, Female with Very Bad health, holding the other variable constant:
The Intercept (£12,116) is the predicted net income per capita for the reference group: females with Very Bad health.
The association of sexMale is positive and statistically significant (+£2,091, p < 0.001): men have £2,091 more net income per capita than women with the same health status, indicating a gender gap in income.
The associations of healthBad and healthFair are not statistically significant (p = 0.90 and 0.18): there is no evidence that their net income per capita differs from people in Very Bad health.
The associations of healthGood and healthVery Good are positive and statistically significant (+£2,766 and +£4,932, both p < 0.001): compared with people in Very Bad health, people in Good and Very Good health have £2,766 and £4,932 more net income per capita respectively, suggesting that income rises with better health.
We then read R-squared and Adjusted R-squared to evaluate the model fit. Both are only around 0.016, meaning sex and health together explain only 1.6% of the variation in Net_inc_pp. The model is therefore poor for prediction, and more variables (e.g. education level, occupation, age) would be needed to explain income better. Even so, the F-test is highly significant (p < 2.2e-16), so the income gaps by gender and health identified above are real, even though they explain only a small part of why incomes differ.
4.3Implementing a linear regression model with a qualitative independent variable
To gain further practice on using linear regression models with qualitative variables as independent variables, we extend the model you created last week by adding the qualitative/categorical variable Region from the Census 2021 dataset. This allows us to answer Research Question 2: How does health vary across regions in England and Wales? We use the dataset EW_DistrictPercentages.csv, which is already in your ‘data/Census2021’ folder.
The practical is split into two main parts. The first focuses on implementing a linear regression model with a qualitative independent variable. Note that you first need to set the reference category (baseline), as the outcomes of the model reflect the differences between each category and the baseline. The second part focuses on prediction based on the estimated linear regression model.
First we load the UK district-level census dataset.
# load dataLAcensus <-read.csv("../data/Census2021/EW_DistrictPercentages.csv") # Local authority level
Using the district-level census dataset “EW_DistrictPercentages.csv”, the variable “Region” (labelled as Government Office Region) is used to explore regional inequality in health.
Familiarise yourself with the dataset by using the same code as last week:
#view the data View(LAcensus) glimpse(LAcensus)
The names() function returns all the column names.
names(LAcensus)
The dim() function simply returns the number of rows and number of columns.
dim(LAcensus)
[1] 331 161
There are 331 rows and 151 columns in the dataset. It would be very hard to scan through the data if we use so many variables altogether. Therefore, we can select several columns to tailor for this practical. You can of course include other variables you are interested in also by their names:
pct_Longterm_sick_or_disabled pct_No_qualifications pct_Males
Min. :1.330 Min. : 6.61 Min. :46.77
1st Qu.:2.865 1st Qu.:15.06 1st Qu.:48.62
Median :3.810 Median :17.63 Median :48.98
Mean :4.013 Mean :17.90 Mean :48.97
3rd Qu.:4.800 3rd Qu.:20.41 3rd Qu.:49.30
Max. :9.110 Max. :28.88 Max. :55.02
pct_Higher_manager_prof Region
Min. : 5.49 Length:331
1st Qu.: 9.79 Class :character
Median :12.34 Mode :character
Mean :13.22
3rd Qu.:15.80
Max. :39.68
Now we can retrieve the “Region” column from the data frame by simply using df$Region. But what if we want to understand the data better, like the following questions?
Q3. Categories of Region
How many categories does the variable “Region” entail? How many local authority districts does each region include?
Simply using the function table() will return the answer.
table(df$Region)
East East Midlands London
45 35 33
North East North West South East
12 39 64
South West Wales West Midlands
30 22 30
Yorkshire and The Humber
21
The table() function tells us that this data frame contains 10 regions, and the number of LAs belonging to each region.
R can only include categorical variables as the factor type, so we set the column Region to factor()
df$Region<-factor(df$Region)
4.3.1Include the categorical variables into a regression model
<<<<<<< Updated upstream We will continue with a very similar regression model fitted in last week that relates percentage long-term illness (pct_Longterm_sick_or_disabled) to percentage no-qualification (pct_No_qualifications), Percentage Males (pct_Males) and Percentages Higher Managerial or Professional occupation (pct_Higher_manager_prof). ======= We will continue with a regression model very similar to the one fitted last week, which relates the percentage of people with long-term sickness or disability (pct_Longterm_sick_or_disabled) to the percentage of people with no qualifications (pct_No_qualifications), the percentage of males (pct_Males) and the percentage of people in higher managerial or professional occupations (pct_Higher_manager_prof). This time, we also add the categorical variable Region. >>>>>>> Stashed changes
R will automatically convert Region into dummy variables, so you don’t need to create them yourself. However, you do need to tell R which region is the baseline (reference category). The principle is simple: if you want to compare the (average) long-term illness rate of Region A with those of the other regions, choose Region A as the baseline. For example, to compare London with the rest of England and Wales, London should be the baseline.
<<<<<<< Updated upstream Implement the regression model with the categorical variables - Region in our case. R will automatically handle the qualitative variable as dummy variables, so you don’t need to worry about any of that. But you need to let R know which category of your qualitative variable is your reference category or the baseline. Here we will use London as our first go. Note: We choose London as the baseline category so the London region will be excluded in the independent variable list. ======= Here we will use London as our first go. Note: because London is the baseline, it will be excluded from the list of Region dummy variables in the output; every other region’s coefficient shows how it differs from London. >>>>>>> Stashed changes
Therefore, first, we set London as the reference:
df$Region <-fct_relevel(df$Region, "London")
Similar to last week, we build our linear regression model, but also include the Region variable into the model.
model <-lm(pct_Longterm_sick_or_disabled ~ pct_Males + pct_No_qualifications + pct_Higher_manager_prof + Region, data = df)summary(model)
Call:
lm(formula = pct_Longterm_sick_or_disabled ~ pct_Males + pct_No_qualifications +
pct_Higher_manager_prof + Region, data = df)
Residuals:
Min 1Q Median 3Q Max
-1.73799 -0.42623 -0.08528 0.41308 2.20676
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 7.615375 3.018425 2.523 0.01212 *
pct_Males -0.167291 0.061638 -2.714 0.00701 **
pct_No_qualifications 0.251334 0.023179 10.843 < 2e-16 ***
pct_Higher_manager_prof 0.007145 0.020244 0.353 0.72438
RegionEast -0.760329 0.173260 -4.388 1.56e-05 ***
RegionEast Midlands -0.254826 0.194419 -1.311 0.19090
RegionNorth East 1.164153 0.260808 4.464 1.12e-05 ***
RegionNorth West 0.784897 0.192449 4.078 5.74e-05 ***
RegionSouth East -0.328575 0.165728 -1.983 0.04827 *
RegionSouth West 0.096484 0.214507 0.450 0.65317
RegionWales 1.382217 0.220643 6.264 1.21e-09 ***
RegionWest Midlands -0.415570 0.196345 -2.117 0.03508 *
RegionYorkshire and The Humber -0.118795 0.217473 -0.546 0.58528
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.7086 on 318 degrees of freedom
Multiple R-squared: 0.7593, Adjusted R-squared: 0.7502
F-statistic: 83.6 on 12 and 318 DF, p-value: < 2.2e-16
You have already learnt how to interpret the output of regression model last week: Significance (p-value), Coefficient Estimates, and Model fit (R squared and Adjusted R-squared).
Q4. Regional differences compared with London
Relating back to this week’s lecture notes, indicate what regions have statistically significant differences in the percentage of long-term illness, compared to London?
First, the Significance and the Coefficient Estimates. The p-values in the last column of the output table show that most of the independent variables are significant predictors of pct_Longterm_sick_or_disabled. All coefficients below are interpreted when the other predictors remain the same.
The Intercept (7.62) is the predicted long-term sick/disabled rate for a London district (the reference category) when pct_Males, pct_No_qualifications and pct_Higher_manager_prof are all 0%. Since no real district has 0% males, we do not interpret this value directly; it is the baseline value to which the other coefficients are added when making predictions.
Continuous variables. Similar to last week, pct_No_qualifications is significant at the <0.001 level (three asterisks ***), indicating a highly statistically significant relationship. We are slightly less confident about pct_Males, which is significant at the <0.01 level (two asterisks **). Their coefficient estimates tell us that:
The association of pct_No_qualifications is positive and statistically significant (+0.25, p < 0.001): each 1% increase in residents with no qualifications is associated with a 0.25% increase in the long-term sick/disabled rate, when the other predictors remain the same.
The association of pct_Males is negative and statistically significant (−0.17, p < 0.01): each 1% increase in males is associated with a 0.17% decrease in the long-term sick/disabled rate, when the other predictors remain the same.
The association of pct_Higher_manager_prof is not statistically significant (p = 0.72).
Region dummy variables. R has created a dummy variable (the items starting with Region) for every region except the reference category, London. Each coefficient therefore shows how much higher (positive) or lower (negative) a region’s long-term sick/disabled rate is compared with London, when the other predictors remain the same:
Significant at the <0.001 level (***):RegionEast, RegionNorth East, RegionNorth West and RegionWales. For example, the North East has a 1.16% higher rate than London, and Wales a 1.38% higher rate, while the East has a 0.76% lower rate.
Significant at the 0.05 level (*):RegionSouth East and RegionWest Midlands. This is weaker evidence than ***, so they are only mildly statistically significant.
Not significant:RegionEast Midlands, RegionSouth West and RegionYorkshire and The Humber, meaning their rates are not significantly different from London’s.
You can interpret the other regions in the same way using their coefficient estimates.
Reminder: You cannot tell from this output whether North East and Wales, or any two regions other than London, are significantly different from each other, because each region’s coefficient only compares that region with London. To compare North East and Wales, set either of them as the reference category, using df$Region <- fct_relevel(df$Region, "North East") or df$Region <- fct_relevel(df$Region, "Wales"), and re-run the model.
Last but not least, the Model Fit. R-squared (0.759) and Adjusted R-squared (0.750) are both around 0.75: the model explains 75.9% of the variation in the long-term sick/disabled rate across districts, or 75.0% after adjusting for the number of independent variables. Together, they suggest a strong fit of the model.
4.3.2Change the baseline category
If you would like to learn about differences in long-term illness between the North West and other regions in England and Wales, you need to change the baseline category from London to the North West region.
df$Region <-fct_relevel(df$Region, "North West")
The regression model is specified again as follows:
Call:
lm(formula = pct_Longterm_sick_or_disabled ~ pct_Males + pct_No_qualifications +
pct_Higher_manager_prof + Region, data = df)
Residuals:
Min 1Q Median 3Q Max
-1.73799 -0.42623 -0.08528 0.41308 2.20676
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 8.400272 3.042017 2.761 0.006090 **
pct_Males -0.167291 0.061638 -2.714 0.007009 **
pct_No_qualifications 0.251334 0.023179 10.843 < 2e-16 ***
pct_Higher_manager_prof 0.007145 0.020244 0.353 0.724376
RegionLondon -0.784897 0.192449 -4.078 5.74e-05 ***
RegionEast -1.545226 0.158845 -9.728 < 2e-16 ***
RegionEast Midlands -1.039723 0.165225 -6.293 1.03e-09 ***
RegionNorth East 0.379256 0.235090 1.613 0.107685
RegionSouth East -1.113472 0.152463 -7.303 2.27e-12 ***
RegionSouth West -0.688413 0.182460 -3.773 0.000192 ***
RegionWales 0.597320 0.189607 3.150 0.001786 **
RegionWest Midlands -1.200467 0.174076 -6.896 2.89e-11 ***
RegionYorkshire and The Humber -0.903692 0.191943 -4.708 3.74e-06 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.7086 on 318 degrees of freedom
Multiple R-squared: 0.7593, Adjusted R-squared: 0.7502
F-statistic: 83.6 on 12 and 318 DF, p-value: < 2.2e-16
Examining R-squared to measure the model fit. How robust is the new model? What % of the variance in the dependent variable has been explained?
Now, complete the following table.
Region names
Higher or lower than North West
Whether the difference is statistically significant (Yes or No)
East Midlands
East
North East
South East
London
West Midlands
Yorkshire and The Humber
Wales
Check the answer at the end of this practical page.
Now it is very easy to use your model to estimate the results Y (dependent variable - pct_Longterm_sick_or_disabled ) by setting all the input independent variable X (pct_Malespct_No_qualifications and pct_Higher_manager_prof).
4.3.3 Recode the Region variable and explore regional inequality in health
In many real-world studies, we might not be interested in health inequality across all regions. For example, in this case study, we are interested in health inequality between London, South, North, Midland and Wales. We can achieve this by re-grouping regions in England and Wales based on the variable “Region”. That said, we need to have a new grouping of regions as follows:
Original region labels
New region labels
East Midlands
Midlands
East
South
London
London
North East
North
North West
North
South East
South
South West
South
West Midlands
Midlands
Yorkshire and The Humber
North
Wales
Wales
Here we use mutate() function in R to make it happen:
This code may look a bit complex. You can simply type ?mutate in your console. In the Help window on the right, RStudio gives you the explanation of the mutate function. This is a common way to use RStudio to help you learn what a function does. mutate() creates new columns that are functions of existing variables. Therefore, the df %>% mutate() means add a new column into the current dataframe df; the New_region_label in the mutate() function indicates the name of this new column is New_region_label. The right side of the New_region_label = indicates the value we want to assign to the New_region_label in each row.
The right side of New_region_label is
fct_collapse(Region, North = c("North East", "North West", "Yorkshire and The Humber"), Midlands = c("East Midlands", "West Midlands"), South = c("East", "South East", "South West"), London = "London", Wales = "Wales")
By using the code, the fct_collapse() function recodes or groups each value in the Region column into one of the broader categories: “London”, “South”, “North”,“Midlands” or “Wales”. Specifically, it takes the existing factor levels in Region and collapses multiple detailed regions into fewer, aggregated groups. For example, regions such as “North East”, “North West”, and “Yorkshire and The Humber” are all grouped under “North”, while “East Midlands” and “West Midlands” are combined into “Midlands”, and so on.
Now we use the same way to examine our new column New_region_label:
table(df$New_region_label)
North London South Midlands Wales
72 33 139 65 22
Comparing with Region, we can now see that the mutate worked:
df[,c("Region","New_region_label")]
Now you will have a new qualitative variable named New_region_label in which England and Wales are divided into five groups: London, South, North, Midlands and Wales.
Based on the newly generated qualitative variableNew_region_label, we can now build our new linear regression model. Don’t forget:
(1) R needs the categorical variables in a regression model to be of the factor type;
class(df$New_region_label)
[1] "factor"
The class() returns the type of the variable. The New_region_label is already a factor variable. If not, we need to convert it by the as.factor(), as we used above.
Are there statistically significant differences in the percentage of people with long-term sick/disable between London and North, and between South and Wales, controlling for other variables? What conclusions could be drawn in terms of regional differences in health outcome?
4.4 Predictions using fitted regression model
Write down the % long term sick or disabled regression model with the new region label categorical variables.
Relating to this week’s lecture, the % pct_Longterm_sick_or_disabled is equal to:
[write down the model]
Q6. Predicting long-term illness in Wales and London
Now imagine that the values of variables pct_Males, pct_No_qualifications, and pct_Higher_manager_prof are 49, 23 and 11, respectively, what would the percentage of persons with long-term sick/disable in Wales and London be?
Check the answer at the end of this practical page.
4.5Answers to the Questions
4.5.1 Q1 associations with health status
Using the Chi-squared test and Cramér’s V, Table 1 can be completed as follows:
Covariates
Cramér’s V
p-value
health
age_group
0.329
< 0.001
health
highest_qual
0.287
< 0.001
health
nssec
0.280
< 0.001
health
marital_status
0.229
< 0.001
All four associations are statistically significant (p < 0.001). Age group has the strongest association with health status (Cramér’s V = 0.329), and marital status the weakest (0.229). Remember that Cramér’s V tells us the strength of an association, but not its direction.
4.5.2 Q2: income inequality by gender and health status
Gender: men have £2,091 more net income per capita than women with the same health status (p < 0.001), indicating a significant gender gap in income.
Health: compared with people in Very Bad health, people in Good and Very Good health have £2,766 and £4,932 more net income per capita respectively (both p < 0.001). The differences for Bad and Fair health are not statistically significant.
Model fit: sex and health explain only 1.6% of the variation in income (R² = 0.016), so other factors matter much more. However, the income gaps by gender and health are statistically significant.
4.5.3 Q3: categories of Region
table(df$Region) shows 10 regions with 331 local authority districts in total: East (45), East Midlands (35), London (33), North East (12), North West (39), South East (64), South West (30), Wales (22), West Midlands (30) and Yorkshire and The Humber (21).
4.5.4 Q4: regions that differ significantly from London
Holding the other predictors constant, compared with London:
Significantly higher: Wales (+1.38%), North East (+1.16%) and North West (+0.78%), all p < 0.001.
Significantly lower: East (−0.76%, p < 0.001), West Midlands (−0.42%, p < 0.05) and South East (−0.33%, p < 0.05).
Not significantly different: East Midlands, South West, and Yorkshire and The Humber.
4.5.5 Changing the baseline to North West
R-squared (0.759) and Adjusted R-squared (0.750) are exactly the same as in the model with London as the baseline. Changing the reference category does not change the model fit; it only changes which comparisons the Region coefficients show.
Region names
Higher or lower than North West
Statistically significant?
East Midlands
Lower (−1.04%)
Yes
East
Lower (−1.55%)
Yes
North East
Higher (+0.38%)
No (p = 0.11)
South East
Lower (−1.11%)
Yes
South West
Lower (−0.69%)
Yes
London
Lower (−0.78%)
Yes
West Midlands
Lower (−1.20%)
Yes
Yorkshire and The Humber
Lower (−0.90%)
Yes
Wales
Higher (+0.60%)
Yes
Note that London is 0.78% lower than North West, which is the same size as the North West coefficient in the London-baseline model (+0.78%), with the opposite sign.
4.5.6 Q5: London vs North, and South vs Wales
London vs North: yes. With London as the baseline, the North has a 0.47% higher long-term sick/disabled rate than London (p = 0.012), when the other predictors remain the same.
South vs Wales: this cannot be answered from model2, because both South and Wales are compared only with London. To test it, set one of them as the reference category, e.g. df$New_region_label <- fct_relevel(df$New_region_label, "South"), and re-run the model. Doing so shows that Wales has a 1.76% higher rate than the South (p < 0.001).
Conclusion: after controlling for sex, qualifications and occupation, model2 tells us how each region compares with London: Wales (+1.25%) and the North (+0.47%) have significantly higher long-term sick/disabled rates than London, while the South (−0.51%) and the Midlands (−0.41%) have significantly lower rates. This suggests clear regional inequalities in health across England and Wales.
Reminder: these conclusions are all relative to London. Although the coefficients suggest an ordering (e.g. Wales appears higher than the North, and the North higher than the South), model2cannot tell us whether the differences between two non-London regions are statistically significant. To test any such comparison, the model must be re-built with one of those regions as the reference category, as we did above for South vs Wales.
4.5.7 The written-down model and Q6
The model of the new region label is: pct_Longterm_sick_or_disabled (%) = 9.98+ (-0.1842)* pct_Males (%) + 0.2014 * pct_No_qualifications (%) + (-0.0341) * pct_Higher_manager_prof + (0.4742) * North + (-0.5063) * South + (-0.4103) * Midlands + 1.2518 * Wales, where North, South, Midlands and Wales are dummy variables (1 if the district is in that region, 0 otherwise). London is the reference category, so all four dummies are 0 for London. Note that pct_Higher_manager_prof is not statistically significant at the 0.05 level (p = 0.087).
If pct_Males, pct_No_qualifications and pct_Higher_manager_prof are 49, 23 and 11:
Wales (Wales = 1, other dummies = 0): 9.98 + (-0.1842)*49 + 0.2014*23 + (-0.0341)*11 + 1.2518*1
Therefore, the predicted percentages of persons with long-term illness in Wales and London are 6.47% and 5.22% respectively. The difference (1.25%) is exactly the Wales coefficient, because the two districts have the same values for all the other predictors. If you got the right answers, congratulations: you can now use a regression model to make predictions!