week8
Table of contents
- Relationships with categorical variables
- One numerical and one categorical variable
- Binary outcomes
- Scatterplots across groups
- Transport and residence
- What have we learned?
- This week’s material
- Looking ahead
- Appendix: R code
1. Relationships with categorical variables
1.1 Two categorical variables
When analyzing two categorical variables, we can examine their joint and marginal distributions, as well as conditional distributions. The joint distribution describes the frequency or proportion of observations that fall into specific combinations of categories for the two variables.
The marginal distribution, on the other hand, summarizes the distribution of a single variable, ignoring the other by summing across its categories. Conditional distributions focus on the distribution of one variable given a specific category of the other variable, effectively changing the denominator for calculating proportions 4 5.
- Joint distribution: Describes combinations of two variables. For example, the number of people who support a specific team and live in a particular city 4.
- Marginal distribution: Sums over the other variable to show the distribution of a single variable. This is calculated using row or column totals from a two-way table 5.
- Conditional distribution: Restricts the denominator to a specific group, showing the distribution of one variable given a category of another. This can be calculated by conditioning on rows or columns of a two-way table 8.
6.
7.
1.2 Independence and dependence
Two categorical variables are considered independent if the conditional distribution of one variable is the same for every category of the other variable, and this distribution is also equal to the marginal distribution of that variable. If the conditional distributions differ from the marginal distribution, the variables are dependent.
Independence is a symmetric relationship; if variable X is independent of variable Y, then Y is also independent of X 12 13.
- Independence: Occurs when the distribution of one variable does not change across categories of another variable. For example, if height distributions are the same for both low and high income groups, height and income are independent 12.
- Dependence: Occurs when the distribution of one variable changes across categories of another variable. For instance, if team preferences vary significantly among residents of different cities, then team supported and city of residence are dependent 11.
1.3 Recap of distributions
This exercise involves analyzing a two-way table of supermarket visits by time of day. It requires calculating joint and marginal distributions, as well as conditional distributions, and visualizing the marginal distribution of time of day 14.
- Joint distribution: The absolute frequency of (X = Mercadona, Y = Morning) is 10 visits. The relative frequency is 10/100 = 10%.
- Marginal distribution of supermarket: Bonpreu has a relative frequency of 60/100 = 60%, and Mercadona has a relative frequency of 40/100 = 40%.
- Conditional distribution of time given Mercadona: The relative frequency of Morning visits conditioned on X = Mercadona is 24/40 = 60%.
- Conditional distribution of supermarket given Morning: The relative frequency of Mercadona conditioned on Y = Morning is 24/36 ≈ 66.7%.
- Bar plot of marginal distribution of Y: This would show three bars representing Morning, Afternoon, and Evening with heights corresponding to their total visit counts (36, 30, 34 respectively) 14.
1.4 Simpson's paradox
Simpson's paradox describes a phenomenon where an observed association between two categorical variables can disappear or even reverse when a third, confounding variable is taken into account. This occurs because the third variable influences the relationship between the original two variables by affecting their distributions or the proportions within their categories 16.
- Simpson's paradox: A statistical phenomenon where a trend appears in different groups of data but disappears or reverses when these groups are combined.
- Confounding variable: A third variable that can influence the observed association between two other variables, potentially masking or altering the true relationship 16.
1.5 University admissions example
In a university admissions scenario, an apparent association between gender and admission rates was observed when pooling data across all applicants. However, when applicants were grouped by faculty (Engineering and Law), the association between gender and admission rates disappeared within each faculty.
This paradox arose because men and women applied to different faculties in different proportions, and the faculties had different overall admission rates 17 18 19 20.
- Overall admission rates: Men had a 45% admission rate, while women had a 30% admission rate, suggesting men were more likely to be admitted 17.
- Admission rates by faculty: Within the Engineering faculty, both men and women had a 50% admission rate. Within the Law faculty, both genders had a 25% admission rate 19.
- Explanation of the paradox: More men applied to Engineering (80% of men) where admission rates were higher (50%), while more women applied to Law (80% of women) where admission rates were lower (25%). This difference in application proportions across faculties created the apparent gender gap in the pooled data 20.
19.
1.6 Reversing association
Simpson's paradox can also lead to a reversal of the observed association. In such cases, a relationship that appears positive when data is combined might become negative within subgroups, or vice versa.
This highlights the importance of considering potential confounding variables when interpreting associations 21.
- Reversing association: The direction of the relationship between two variables changes when moving from pooled data to subgroup data.
- Illustrative data: Within each group (e.g., Group A, Group B), higher values of variable X are associated with higher values of variable Y. However, when the groups are combined, higher values of X are associated with lower values of Y 21.
2. One numerical and one categorical variable
2.1 Comparing numerical outcomes across groups
This section explores how numerical outcomes, such as income, can be compared across different groups defined by a categorical variable. The comparison focuses on the center, spread, and overlap of the distributions within each group.
Categorical variables can be nominal, meaning they have no natural order (e.g., county of residence), or ordinal, meaning they have a natural order (e.g., education level). Ordinal categories do not necessarily imply equally spaced intervals 23.
2.2 Income by county: a nominal categorical variable
When analyzing income by county, we examine how income distributions differ across these distinct geographical groups. The data includes income in euros and the county of residence for 20 individuals 24.
📝 In the Maresme county, with 4 individuals, the mean income is 13,500 euros, and the standard deviation is 2,887 euros 25.
2.3 Income summaries within counties
Income statistics are summarized for each county, providing the number of individuals (n), mean income, median income, and standard deviation (SD). For example, in the Maresme county, with 4 individuals, the mean income is 13,500 euros, and the standard deviation is 2,887 euros 25.
| County | n | Mean | Median | SD |
|---|---|---|---|---|
| Baix Llobregat | 3 | 15,333 | 16,000 | 4,041 |
| Barcelonès | 4 | 14,500 | 14,500 | 2,082 |
| Maresme | 4 | 13,500 | 13,500 | 2,887 |
| Vallès Occidental | 4 | 19,750 | 20,500 | 2,630 |
| Vallès Oriental | 5 | 24,200 | 23,000 | 3,564 |
2.4 Income distributions within counties
The income distributions within each county are visualized using bar charts. These charts show the percentage of individuals within a county falling into different income brackets (in thousands of euros).
For instance, in Maresme, 75% of individuals earn between 10,000 and 15,000 euros 26.
26.
2.5 Income by county: comparing center and spread
Box plots are used to compare the center and spread of income across different counties. In the provided data, Vallès Oriental exhibits the highest median income at 23,000 euros.
Barcelonès has the smallest interquartile range (IQR), indicating that its middle 50% of incomes are the most tightly grouped 27.
27.
2.6 Income by schooling level: an ordinal categorical variable
Income is also analyzed in relation to schooling level, which is an ordinal categorical variable. The schooling levels are coded from 0 (Illiterate) to 4 (Master), indicating a natural order 28.
📝 The Master group shows the largest standard deviation, indicating greater income variability, with a value of 5,944 euros 29.
2.7 Income summaries within schooling groups
Summary statistics for income are provided for each schooling group, including the number of individuals (n), mean income, median income, and standard deviation (SD). The mean income generally increases with higher levels of schooling.
The Master group shows the largest standard deviation, indicating greater income variability 29.
| Schooling | n | Mean | Median | SD |
|---|---|---|---|---|
| Illiterate | 4 | 13,000 | 13,000 | 2,944 |
| Primary | 4 | 14,000 | 13,500 | 2,160 |
| High School | 4 | 19,500 | 20,500 | 4,041 |
| Bachelor | 4 | 20,000 | 20,500 | 2,160 |
| Master | 4 | 23,000 | 23,000 | 5,944 |
2.8 Income distributions within schooling groups
The income distributions for each schooling group are visualized, showing the percentage of individuals within each group falling into specific income brackets. The Illiterate and Primary groups show more concentrated income ranges, while higher education levels exhibit broader income distributions 30.
30.
2.9 Mean income within schooling groups
A scatter plot illustrates the mean income in euros for different schooling groups, with individual income data points also shown. The mean income for the Illiterate group is 13,000 euros, and for the Master group, it is 23,000 euros.
It is important to note that this observed association does not establish a causal effect of schooling on income 31.
31.
2.10 Income by schooling: center and spread
Box plots are used to visualize the income distribution by schooling level, showing the center and spread. The Master group has the highest median income at 23,000 euros and the widest observed range, from 16,000 to 30,000 euros.
Despite the general trend of increasing income with higher schooling, incomes still overlap across different educational attainment levels 32.
32.
3. Binary outcomes
3.1 Daily smoking and lung cancer
This section explores whether a numerical variable can explain a binary outcome, using the example of daily smoking and lung cancer diagnosis. The data includes 60 illustrative observations to investigate if lung cancer diagnosis becomes more common as the number of cigarettes smoked per day increases 33.
The scatter plot visualizes the relationship between the average number of cigarettes smoked per day and the diagnosis of lung cancer during follow-up. Individual observations are shown as gray dots.
The blue line represents the mean lung cancer diagnosis rate in 10-cigarette bands, plotted at the midpoint of each band. The mean value at each point equals the share of individuals diagnosed with lung cancer within that band 34.

4. Scatterplots across groups
4.1 Wages and experience
Scatterplots can reveal relationships between variables, such as the connection between work experience and wages. While more experience generally correlates with higher wages, there is considerable variation among individuals with similar experience levels.
Adding a categorical variable, like gender, can help explain some of this wage variation.
36.
- Positive correlation: Wages tend to increase as work experience increases.
- Wage variation: Significant differences in wages exist for workers with the same amount of experience 36.
4.2 An increasing gender gap
When a categorical variable like gender is introduced, scatterplots can illustrate differences between groups. In this scenario, the expected wage gap between men and women widens with increasing years of experience.
- Initial gap: At zero years of experience, the expected wage difference is EUR 5,000.
- Gap growth: For each additional year of experience, the wage gap increases by EUR 500.
- Widening disparity: By 20 years of experience, the expected wage gap reaches EUR 15,000 37.
37.
📝 At zero years of experience, the expected wage gap is EUR 5,000. For each additional year of experience, the wage gap increases by EUR 500, reaching EUR 15,000 by 20 years of experience 37.
4.3 A shrinking gender gap
Conversely, a scatterplot can also depict a scenario where the gender wage gap narrows with increased experience. This occurs when the rate of wage increase for women outpaces that for men.
- Equal starting wages: Both men and women begin with the same expected wage at zero experience.
- Narrowing disparity: The wage gap decreases by EUR 200 per year of experience.
- Reduced gap: By 20 years of experience, the expected wage gap shrinks to EUR 1,000 38.
38.
4.4 When would the gender gap reverse?
Extrapolating trend lines beyond the observed data range can suggest potential future scenarios, such as a reversal of the gender wage gap. However, such projections are speculative and depend on the continued validity of the observed trends.
- Projected crossover: The projected wage lines for men and women intersect at 25 years of experience.
- Projected reversal: At 30 years of experience, women are projected to earn slightly more than men.
- Extrapolation: These projections extend beyond the observed data range of 0–20 years and are therefore speculative 39.
39.
4.5 Who earns more overall?
When analyzing a dataset with both men and women, calculating the mean wage for each group can provide an overall comparison. This calculation can reveal differences in average earnings between genders, irrespective of experience levels.
- Sample size: The dataset includes 33 men and 33 women.
- Mean wages: The average wage for men is EUR 47,000, while for women it is EUR 54,000 40.
40.
4.6 Why does the ranking reverse?
Simpson's paradox illustrates how an observed trend in aggregated data can reverse when the data is broken down into subgroups. In wage analysis, this can occur if one group has, on average, significantly more experience than the other, masking a potential difference in wages at equivalent experience levels.
- Observed means: Men's mean wage is EUR 47,000, and women's mean wage is EUR 54,000.
- Experience difference: Women average 16 years of experience, while men average 6 years.
- Underlying trend: At the same level of experience, men are projected to have higher expected wages 41.
41.
📝 Men's mean wage is EUR 47,000, while women's mean wage is EUR 54,000. However, women average 16 years of experience and men average 6 years, and at the same experience level, men have higher expected wages 41.
4.7 Where can we compare expected wages?
Comparing expected wages between groups requires that their experience ranges overlap. When ranges do not overlap, any comparison necessitates extrapolation, making the results less reliable.
- Overlap comparison: Comparisons are reliable within the overlapping range of experience for both groups.
- Extrapolation needed: If experience ranges do not overlap, comparisons require extending the data beyond the observed range for at least one group.
- Example scenario: Comparing at 10 years of experience is possible within the overlap, but comparing at 18 years requires extending the women's data, and at zero years requires extending the men's data 42.
5. Transport and residence
5.1 Commute survey analysis
This section focuses on analyzing survey data related to transportation modes and student residence. The primary goal is to construct a joint distribution table from raw survey responses to answer specific questions about commute habits 44.
The analysis involves calculating various shares of respondents based on their residence and primary transport mode. This helps understand commuting patterns within the student population 44.
5.2 Joint distribution of transport mode and residence
To analyze the survey data, a joint distribution table is constructed. This table cross-tabulates the main transport mode used by respondents against their place of residence 44.
The table allows for the calculation of several key shares:
- The overall share of respondents residing in Barcelona city.
- The share of respondents using each specific transport mode.
- The share of Barcelona city residents who use the metro.
- The share of metro users who live in Barcelona city 44.
The choice of the total (denominator) for each share calculation is crucial for accurate interpretation 44.
5.3 Commute time and days on campus
Further analysis of the survey data explores the relationship between commute times, days spent on campus, and student residence 45.
Key questions addressed include:
- Determining the typical commute time for students living in Barcelona city versus those living outside the city, and assessing the variation in commute times within each group.
- Investigating whether students with longer commutes tend to come to campus fewer days per week, and examining if this relationship differs between the two residence groups 45.
To answer these questions, appropriate statistical plots and calculations would be employed. Comparisons between groups would also consider sample sizes, especially when one group has few responses 45.
📝 To determine the share of Barcelona city residents who use the metro, you would divide the number of respondents who live in Barcelona city AND use the metro by the total number of respondents who live in Barcelona city 44.
6. What have we learned?
6.1 Joint and marginal distributions
Joint distributions describe the probability of two or more variables occurring together, while marginal distributions describe the probability of a single variable irrespective of others. These distributions are fundamental to understanding the relationships between variables in a dataset 46.
- Joint distribution: This describes the probability of multiple variables taking on specific values simultaneously.
- Marginal distribution: This describes the probability of a single variable taking on a specific value, without regard to the values of other variables 46.
6.2 Conditioning on a group
When conditioning on a group, the denominator used is the total number of observations within that specific group. This ensures that probabilities are calculated relative to the size of the subgroup being analyzed 46.
6.3 Conditional distributions under independence
Under independence, conditional distributions are identical to the marginal distributions. This means that knowing the value of one variable does not change the probability distribution of another 46.
6.4 Simpson's paradox
Simpson's paradox occurs when a relationship between two variables reverses or disappears when a third variable is introduced. The pooled relationship can differ from within-group relationships because the third variable may confound the association by influencing both variables of interest 46.
6.5 Comparing numerical summaries across categories
To compare center and spread across categories, one can use numerical summaries such as means, medians, and standard deviations for each group. Visualizations like box plots are also effective for comparing distributions across different categories 46.
6.6 Comparing expected wages across groups
Comparing expected wages across groups involves calculating the average wage for each category. When comparing expected wages across groups, one must consider whether extrapolation is necessary if the data for certain groups is limited 46.
7. This week’s material
7.1 Week 8 lecture slides
The lecture slides for Week 8 cover relationships with categorical variables 47.
📝 The Week 8 lecture slides cover relationships with categorical variables 47.
7.2 Moore, 9e
Chapters 06 and 04 of Moore, 9th edition, are assigned 47.
7.3 Dossier
Section 5.2 of the dossier discusses the relationship between one numerical and one categorical variable 47.
8. Looking ahead
8.1 Next week's topics
This section previews upcoming topics and assessments. Next week's focus will be on time series analysis 48.
8.2 Upcoming assessments
Prepare for Lecture Test 3, which will cover two-variable analysis and combinations. Seminar 7 will focus on testing two categorical variables and will include Practical Case 4 48.
📝 Lecture Test 3 will cover two-variable analysis and combinations, and Seminar 7 will focus on testing two categorical variables, including Practical Case 4.
8.3 Autonomous work
You are required to complete the assigned autonomous-work guide and quiz 48.
8.4 Reading assignment
The reading for next week is Section 8, titled "Time series," from the DOSSIER 49.
9. Appendix: R code
9.1 R code: Joint distribution
This section demonstrates how to represent and calculate joint distributions using R. A joint distribution shows the counts or percentages for combinations of two categorical variables. The example uses a matrix to store counts of people based on their team support and city of residence 51.
- Data structure: A matrix is used to store the counts, with rows representing one variable (e.g., team supported) and columns representing another (e.g., city of residence).
- Calculating percentages: The
prop.table()function in R can be used to convert raw counts into proportions, which can then be multiplied by 100 to get percentages 51.
- Joint distribution example
Given a data matrix representing team support versus city of residence, calculating
100 * prop.table(data)will yield the percentage of the total sample that falls into each combination of team and city 51.
9.2 R code: Marginal distributions
Marginal distributions in R are calculated by summing counts across rows or columns of a joint distribution table. This provides the total counts for each category of a single variable, irrespective of the other variable 52.
- Adding margins: The
addmargins()function can be used to automatically add row and column sums to the data matrix, providing a quick overview of marginal counts. - Calculating row sums:
rowSums(data)calculates the total count for each row (e.g., total supporters for each team). - Calculating column sums:
colSums(data)calculates the total count for each column (e.g., total residents in each city). - Marginal percentages: To find the marginal percentages, divide the row or column sums by the grand total of all observations 52.
📝 To find the marginal distribution of cities, you can calculate
100 * colSums(data) / sum(data)to get the percentage of the total sample residing in each city 52.
9.3 R code: Marginal bar plots
Bar plots are effective for visualizing marginal distributions. R's barplot() function can create these plots, allowing for clear representation of counts for each category of a single variable 53.
- City of residence plot: A bar plot can be generated for the column sums (city residents), with ylim setting the y-axis limit and
mainandylabproviding plot titles and labels. - Team supported plot: Similarly, a bar plot can be created for the row sums (teams supported), using the same customization options 53.
9.4 R code: Joint bar plots
Joint distributions can be visualized using bar plots in R, which can display the counts for combinations of two variables. The barplot() function with the beside = TRUE argument creates grouped bar plots, while omitting it creates stacked bar plots 54.
- Grouped bars:
barplot(data, beside = TRUE, legend.text = TRUE)displays bars for each category of the second variable side-by-side within each category of the first variable. - Stacked bars:
barplot(data, beside = TRUE, legend.text = TRUE)(withoutbeside = TRUE) stacks the bars, showing the composition of each category of the first variable. - Transposing data: Transposing the data matrix (
t(data)) before plotting allows grouping by the other variable 54.
9.5 R code: Conditional distributions
Conditional distributions in R are calculated using the prop.table() function with a specified margin. This allows for the calculation of proportions within specific rows or columns, representing the distribution of one variable given the other 55.
- Distribution within a row:
prop.table(data, 1)calculates proportions for each cell within its row. This answers questions like "Given a team, what is the distribution of cities of residence?". - Distribution within a column:
prop.table(data, 2)calculates proportions for each cell within its column. This answers questions like "Given a city, what is the distribution of teams supported?". - Rounding: The
round()function is often used to present these conditional percentages with a specified number of decimal places 55.
📝 To find the distribution of cities for Barça supporters, calculate
round(100 * prop.table(data, 1), 1)and look at the "Barça" row 55.
9.6 R code: Team given BCN
This example demonstrates how to calculate and visualize the conditional distribution of teams supported, given that the resident lives in Barcelona. It involves subsetting the data to include only Barcelona residents and then calculating the percentage distribution of teams within that group 56.
- Subsetting data:
data[, "BCN"]selects the column corresponding to Barcelona residents. - Calculating percentages: The selected counts are then divided by their sum (
sum(counts)) and multiplied by 100 to get the percentage of Barcelona residents supporting each team. - Visualization: A bar plot is used to display these percentages, with the y-axis labeled to indicate it represents the percent of Barcelona residents 56.
9.7 R code: City given Barça
This section illustrates calculating and visualizing the conditional distribution of cities of residence, given that the individual supports Barça. It involves subsetting the data for Barça supporters and then determining the percentage distribution of cities among them 57.
- Subsetting data:
data["Barça", ]selects the row corresponding to Barça supporters. - Calculating percentages: The selected counts are divided by their sum (
sum(counts)) and multiplied by 100 to show the percentage of Barça supporters residing in each city. - Visualization: A bar plot visualizes these percentages, with the y-axis clearly indicating it represents the percent of Barça supporters 57.
9.8 R code: Team distributions within cities
This code demonstrates how to visualize the distribution of teams supported within each city. It calculates the proportion of supporters for each team within each city and then uses bar plots to display these conditional distributions 58.
- Calculating shares:
prop.table(data, 2)calculates the proportion of each team's supporters within each city (column). - Grouped bar plot:
barplot(shares, beside = TRUE, legend.text = TRUE)displays these proportions side-by-side for each city, allowing for easy comparison of team support across cities. - Stacked bar plot:
barplot(shares, legend.text = TRUE)stacks the proportions within each city, showing the relative contribution of each team to the total supporters in that city 58.
9.9 R code: Height within income groups
This example shows how to analyze the distribution of height (Short/Tall) within different income groups (Low/High). It calculates the conditional distributions and also includes the overall marginal distribution of height 59.
- Data setup: A matrix
datais created with rows for income groups and columns for height categories. - Conditional distributions:
prop.table(data, 1)calculates the percentage of short and tall individuals within each income group (row). - Marginal distribution: The overall percentage of short and tall individuals across all income groups is calculated using
colSums(data) / sum(data). - Combining results: The
rbind()function combines the conditional percentages with the marginal percentages into a single table for comparison 59.
9.10 R code: Income within height groups
This section reverses the perspective from the previous example, analyzing the distribution of income groups (Low/High) within different height groups (Short/Tall). It calculates conditional distributions and the overall marginal distribution of income 60.
- Data setup: The data matrix is transposed (
t(data)) so that rows represent height groups and columns represent income groups. - Conditional distributions:
prop.table(t(data), 1)calculates the percentage of low and high income individuals within each height group (row). - Marginal distribution: The overall percentage of low and high income individuals across all height groups is calculated using
rowSums(data) / sum(data). - Combining results:
rbind()combines the conditional percentages with the marginal percentages for comparison 60.
9.11 R code: Income summaries by county
This section demonstrates how to calculate summary statistics (count, mean, median, standard deviation) for income, broken down by county, using data from an external Excel file 61.
- Loading data: The
openxlsxlibrary is used to read data from an Excel file (non_ranked.xlsx). - Splitting data:
split(non_ranked$income, non_ranked$county)divides the income data into separate lists, one for each county. - Calculating statistics:
lengths(),sapply(income, mean),sapply(income, median), andsapply(income, sd)are used to compute the count, mean, median, and standard deviation for each county's income data, respectively. - Combining results:
cbind()combines these statistics into a single table, which is then rounded for readability 61.
9.12 R code: Income bins by county
This example shows how to categorize income data into bins (intervals) and then count the number of individuals within each bin for each county. It uses the cut() function to create the bins and table() to count occurrences 62.
- Defining breaks:
seq(10000, 35000, by = 5000)creates a sequence of numbers defining the boundaries for income bins (e.g., 10000-14999, 15000-19999, etc.). - Creating bins:
cut(non_ranked$income, breaks, right = FALSE, include.lowest = TRUE)assigns each income value to a bin.right = FALSEmeans intervals are closed on the left and open on the right (e.g.,[10000, 15000)).include.lowest = TRUEensures the lowest value is included. - Counting within bins:
table(non_ranked$county, bin)creates a contingency table showing the counts of incomes within each bin for each county. - Calculating percentages:
prop.table(counts, 1)converts these counts into percentages within each county (row), showing the distribution of income bins for each county 62.
📝 To see the distribution of income bins for each county, use
percent <- 100 * prop.table(counts, 1)after creating income bins withcut()and counting them withtable()62.
9.13 R code: County medians and IQRs
This section focuses on calculating the median income and interquartile range (IQR) for each county, using data previously loaded from non_ranked.xlsx 63.
- Grouping income:
split(non_ranked$income, non_ranked$county)groups the income data by county. - Calculating median:
sapply(income, median)computes the median income for each county. - Calculating IQR:
sapply(income, IQR)computes the IQR for income in each county. - Combining results:
cbind()combines the median and IQR into a table, showing these measures for each county 63.
9.14 R code: Schooling summary
This section demonstrates calculating summary statistics (count, mean, median, standard deviation) for income, categorized by schooling level, using data from an external Excel file (ranked.xlsx) 64.
- Loading data: The
openxlsxlibrary is used to read data from theranked.xlsxfile. - Splitting data:
split(ranked$income, ranked$schooling)separates the income data into lists, with each list corresponding to a specific schooling level. - Calculating statistics:
lengths(),sapply(income, mean),sapply(income, median), andsapply(income, sd)are used to compute the count, mean, median, and standard deviation of income for each schooling level. - Combining results:
cbind()merges these statistics into a single table, which is then rounded for clarity 64.
9.15 R code: Income bins by schooling level
This example illustrates how to bin income data into specified intervals and then count the occurrences within each bin for each schooling level. It uses the cut() function for binning and table() for counting 65.
- Defining breaks:
seq(10000, 35000, by = 5000)defines the boundaries for the income bins. - Creating bins:
cut(ranked$income, breaks, right = FALSE, include.lowest = TRUE)assigns each income value to its corresponding bin, with intervals closed on the left. - Counting within bins:
table(ranked$schooling, bin)generates a table showing the counts of incomes within each bin for each schooling level. - Calculating percentages:
prop.table(counts, 1)converts these counts into percentages within each schooling level (row), displaying the income bin distribution for each level 65.
9.16 R code: Schooling means
This section visualizes the relationship between income and schooling level by plotting individual incomes and then overlaying the mean income for each schooling level 66.
- Grouping income:
split(ranked$income, ranked$schooling)groups income data by schooling level. - Calculating means:
sapply(income, mean)calculates the average income for each schooling level. - Plotting individual incomes:
stripchart()creates a plot showing individual income points for each schooling level. - Adding group means:
points(seq_along(means), means, pch = 18, col = "blue", cex = 1.5)adds distinct markers for the mean income of each schooling group onto the plot 66.
9.17 R code: Schooling box
This example uses boxplots to visualize the distribution of income across different schooling levels. Boxplots provide a summary of the data, including median, quartiles, and potential outliers 67.
- Creating boxplots: The
boxplot(income ~ schooling, data = ranked,...)function generates boxplots, withincomeas the variable being plotted andschoolingas the grouping variable. - Customization: Arguments like
xlab,ylab,col, andcex.axisare used to customize the plot's labels, color, and axis text size for better readability 67.
© 2026 Maeve. All rights reserved. This content is protected by copyright.