Exercises B
Programming and Data Analysis with R
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.
Write a function
var2(x)that computes the variance using the definition.Write a function
var3(x)that computes the variance using the formula based on the distances between pairs of elements.Suppose that
x = c(1, 4, 2, 2, 10). Check that the two functionsvar2(x)andvar3(x)return the same result.Suppose now that
x <- 1:3000. Computevar2(x)andvar3(x). Which of the two functions is slower, and why?Compare the functions
var2andvar3with the functionvarimplemented 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.
Load the data into memory. The file has the
.RDataformat: use the commandload(see the documentation).Which variables does the dataset
electionscontain? Of which type are they?Build the contingency table of
partyanddistrict, that is the number of votes obtained by each party in each district.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.
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.Write a function
Gini_norm(x)that computes the normalised Gini index, that is G_\text{norm} = \frac{k}{k-1} G.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.
Import the data into R and create a second data frame, without the row relative to
DC.Using the data without
DC, compute the mean and the standard deviation ofmurder. In which unit of measurement are they expressed?Still without
DC, find the quartiles ofmurderwith the commandsummaryand draw its boxplot. Is there any outlier? Which state is it?Include
DCagain. 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.
Import the data into R. The
read.tablefunction 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 ofprice, using the classes (0, 100], (100, 200], \dots, (800, 900]. Is the distribution symmetric or skewed?Construct a boxplot of
priceand interpret it. Are there unusually high prices?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 ofpriceand oflog(price): in which case are they closer?How many houses are new? Compute the summary statistics (command
summary) ofpriceseparately 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?Let now y =
priceand 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?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
- 1000 square feet, (ii) 4000 square feet.
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.
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?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?Study the association between
CO2andGDPthrough a scatterplot, the correlation and the least squares line, as in Unit F. Find the predicted CO_2 for the smallest and for the largestGDPin this sample.The correlation between
GDPandPrisonis 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.
Import the data into R. How many sheep are there? How many of them survived?
Compute the mean, the median and the standard deviation of
weight, separately for the sheep that survived and for those that did not.Draw the boxplots of
weightfor the two groups side by side.Are the sheep that survived heavier, on average? Can you conclude that being heavier causes a sheep to survive?