Exercises B

Programming and Data Analysis with R

Author
Affiliation

Tommaso Rigon

Università degli Studi di Milano-Bicocca

Homepage

These exercises accompany Units D, E, F and G.

The exercises whose title carries a number such as (AK 1.17) are taken from Chapter 1 of Agresti and Kateri (2022); their data are those of the website of the book.

The solution of each exercise is in a separate R script, linked from the title of the exercise itself.

Writing your own functions

The variance of the data y_1,\dots,y_n is defined as

\text{var}(y) = \frac{1}{n}\sum_{i=1}^n(y_i - \bar{y})^2, where \bar{y} is the sample mean. Note that \text{var}(y) admits the alternative representation

\text{var}(y) = \frac{1}{2 n^2} \sum_{i=1}^n \sum_{j = 1}^n (y_i - y_j)^2.


  1. Write a function var2(x) that computes the variance using the definition.

  2. Write a function var3(x) that computes the variance using the formula based on the distances between pairs of elements.

  3. Suppose that x = c(1, 4, 2, 2, 10). Check that the two functions var2(x) and var3(x) return the same result.

  4. Suppose now that x <- 1:3000. Compute var2(x) and var3(x). Which of the two functions is slower, and why?

  5. Compare the functions var2 and var3 with the function var implemented in R, using the data of point 3. Why do the results differ, even if only slightly? Consult the documentation to answer.

Data analysis

At this link the data of the 2016 municipal elections in the city of Milan are available. Each statistical unit is a single vote; the variable party reports the list the vote was cast for, and the variable district the borough (Municipio) in which it was cast.


  1. Load the data into memory. The file has the .RData format: use the command load (see the documentation).

  2. Which variables does the dataset elections contain? Of which type are they?

  3. Build the contingency table of party and district, that is the number of votes obtained by each party in each district.

  4. Compute the number of votes obtained by each party in the whole city and draw a barplot of it. Compute moreover the percentage of votes obtained by each party, rounded to two decimal digits.

  5. Write the function Gini(x) that computes the Gini index for a qualitative variable. The Gini index is defined as G = 1 - \sum_{j=1}^k f_j^2, where f_1,\dots,f_k are the relative frequencies of the k categories.

  6. Write a function Gini_norm(x) that computes the normalised Gini index, that is G_\text{norm} = \frac{k}{k-1} G.

  7. Evaluate the fragmentation of the votes among the parties in the different districts using the normalised Gini index. Organise the results in a table and say which district is the most fragmented and which one is the most concentrated, that is the one in which the votes are polarised towards a few parties. Pay attention to the direction of the index: a Gini index close to 1 means that the votes are spread evenly across the parties.

The Murder data file of Agresti and Kateri (2022), available at this link, reports the murder rate (number of murders per 100{,}000 inhabitants) of each of the 50 states of the U.S. and of the District of Columbia (DC), according to the FBI Uniform Crime Reports.

At first, leave the observation relative to DC aside.


  1. Import the data into R and create a second data frame, without the row relative to DC.

  2. Using the data without DC, compute the mean and the standard deviation of murder. In which unit of measurement are they expressed?

  3. Still without DC, find the quartiles of murder with the command summary and draw its boxplot. Is there any outlier? Which state is it?

  4. Include DC again. What is affected more by this outlier: the mean or the median? The range or the interquartile range? Why?

The Houses data file of Agresti and Kateri (2022), available at this link, lists the selling price (price, in thousands of dollars), the size (size, in square feet), the tax bill (taxes, in dollars), the number of bedrooms (bedrooms) and of bathrooms (baths), and whether the house is new (new, 1 = yes, 0 = no) for 100 home sales in Gainesville, Florida.


  1. Import the data into R. The read.table function accepts a web address in place of a file name, so there is no need to download the file first. Construct the frequency table and the histogram of price, using the classes (0, 100], (100, 200], \dots, (800, 900]. Is the distribution symmetric or skewed?

  2. Construct a boxplot of price and interpret it. Are there unusually high prices?

  3. Draw the histogram and the boxplot of the logarithm of the price. Is the distribution more symmetric than the one of price? Compute the mean and the median of price and of log(price): in which case are they closer?

  4. How many houses are new? Compute the summary statistics (command summary) of price separately for new and old houses, and draw the two boxplots side by side. Which group is more expensive? Is the comparison based on enough data?

  5. Let now y = price and x = size. Draw the scatterplot. Is the relationship positive or negative? Identify the largest house: is its price in line with those of the other houses?

  6. Find the correlation and interpret it. Then find the least squares estimates \hat{\alpha} and \hat{\beta}, as in Unit F, interpret the slope, and find the predicted selling price for a house of

    1. 1000 square feet, (ii) 4000 square feet.
  7. Remove the largest house and compute the least squares estimates again. How much do they change?

The UN data file of Agresti and Kateri (2022), available at this link, has United Nations data for 42 nations on the following variables:

  • GDP, the per capita gross domestic product, in thousands of dollars;

  • HDI, a human development index, with components referring to life expectancy at birth, educational attainment and income per capita;

  • GII, a gender inequality index, a composite measure reflecting inequality in achievement between women and men in reproductive health, empowerment and the labour market;

  • Fertility, the fertility rate, that is the number of births per woman;

  • CO2, the carbon dioxide emissions per capita, in metric tons;

  • Homicide, the homicide rate, per 100{,}000 people;

  • Prison, the prison population, per 100{,}000 people;

  • Internet, the percentage of people using the Internet.


  1. Import the data into R. Compute the summary statistics and the standard deviation of Prison, and draw its boxplot. Which nation has the highest prison rate?

  2. Construct the correlation matrix of the eight quantitative variables: the command cor, applied to a data frame of numerical variables, returns the correlations of all the pairs. Which pair has the strongest association?

  3. Study the association between CO2 and GDP through a scatterplot, the correlation and the least squares line, as in Unit F. Find the predicted CO_2 for the smallest and for the largest GDP in this sample.

  4. The correlation between GDP and Prison is essentially zero. Does this mean that the two variables are unrelated? Look at the scatterplot, and then repeat the computation without the United States.

A study of sheep analysed whether a sheep survived for a year from the original observation time (survival, 1 = yes, 0 = no) as a function of its weight, in kg, at the original observation. The Sheep data file of Agresti and Kateri (2022) is available at this link.


  1. Import the data into R. How many sheep are there? How many of them survived?

  2. Compute the mean, the median and the standard deviation of weight, separately for the sheep that survived and for those that did not.

  3. Draw the boxplots of weight for the two groups side by side.

  4. Are the sheep that survived heavier, on average? Can you conclude that being heavier causes a sheep to survive?

References

Agresti, A., and Kateri, M. (2022), Foundations of statistics for data scientists, CRC Press.