Exercises A

Programming and Data Analysis with R

Author
Affiliation

Tommaso Rigon

UniversitĂ  degli Studi di Milano-Bicocca

Homepage

These exercises accompany Units A, B and C. The exercises of the last section require data frames, which are covered in Unit C: come back to those once we have seen the corresponding material.

The exercises whose title carries a number such as (AK 1.2(a)) 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.

Numerical computing and programming

Write in R the function f(x) associated with

f(x) = \frac{|\sin(\pi/(4 x^2))|}{x}, \qquad x \neq 0.

  1. What is the value of f(1)? And of f(10^8)?

  2. Approximate f(1) and f(10) to the first two decimal digits.

  3. Draw a plot of the function f(x) over the interval (1,3).

  4. Compute \sum_{k=1}^{K} f(k), for K = 500.

  5. Difficult. The integrate function of R (see the documentation) makes it possible to compute numerically integrals of the form I = \int_a^b f(x)\mathrm{d}x, where a < b are two real values. Compute the value of the integral \int_1^3 f(x)\mathrm{d}x, where f(x) is the function used in the previous points.

For n = 10, 100, 1000, compute the left-hand side of each of the following identities with the commands sum and choose, and compare it with the right-hand side. For which values of n does R return a wrong result, and why?

  1. \sum_{k=0}^n(-1)^k\binom{n}{k} = 0.

  2. \sum_{k=1}^n k \binom{n}{k} = n 2^{n-1}.

  3. \sum_{k=1}^n(-1)^{k}k \binom{n}{k} = 0.

Write in R a function roots(a, b, c) that takes as input the coefficients of the polynomial

a x^2 + b x + c, and returns the vector of the values of x that make it equal to zero.

  1. Compute roots(1, 5, 2);

  2. Compute roots(1, 2, 1);

  3. Compute roots(1, 1, 1). What does R return, and why?

The Euclidean distance between two vectors {\bf x} and {\bf y} in \mathbb{R}^p is defined as d({\bf x},{\bf y}) = \sqrt{\sum_{j=1}^p(x_j - y_j)^2}, whereas the Frobenius norm ||{\bf A}||_F of a real-valued matrix {\bf A} of dimension n \times m is defined as ||{\bf A}||_F = \sqrt{\sum_{i=1}^n \sum_{j=1}^m a_{ij}^2}.

  1. Write the R function dist_euclid(x, y) that computes the Euclidean distance between two vectors.

  2. If x = c(1, 4, 2, 2, 10) and y = c(8, 1, 8, 3, 6), what is the value of dist_euclid(x, y)?

  3. Write the R function frobenius_norm(A) that computes the Frobenius norm of a matrix A.

  4. If A = cbind(1:5,6:10,11:15), what is the value of frobenius_norm(A)?

  5. Verify that dist_euclid(x, y) and frobenius_norm(x - y) return the same value. Why is that the case?

Let {\bf A} be a matrix of dimension n \times n.

  1. Write a function diag2(A) that, using a for loop, returns the vector of the diagonal elements a_{11}, \dots, a_{nn} of the matrix {\bf A}.

  2. Check that diag2(A) and diag(A) return the same vector for A <- matrix(1:25, nrow = 5).

What does the function f(10) return? Discuss the result without running the following code

h <- function(x) {
  x^2 
}

g <- function(x) {
  h(x) + 1 
}

f <- function(x) {
  g(x) * 2 
}

f(10)

Data frames

The swiss data file, available at this link, reports standardised socio-economic indicators for the 47 French-speaking provinces of Switzerland around 1888:

  • province, the name of the province;

  • Fertility, a standardised fertility measure;

  • Agriculture, the percentage of males employed in agriculture;

  • Examination, the percentage of draftees receiving the highest mark on an army examination;

  • Education, the percentage of draftees educated beyond primary school;

  • Catholic, the percentage of Catholics;

  • Infant.Mortality, the percentage of live births who die within a year.


  1. Import the data into R. How many rows and how many columns does this dataset have? Which type does R assign to the variable province?

  2. Why does the command swiss[1:20] return an error? What is the difference with the command swiss[1:20, ]?

  3. Each of the following lines contains an error (a bug). Propose a modification to fix it

swiss[swiss$Education = 7, ]
swiss[-1:4, ]
swiss[swiss$Education <= 5]
swiss[swiss$Education == 7 | 12, ]

The Students data file of Agresti and Kateri (2022) collects the answers of 60 social science graduate students of the University of Florida to a questionnaire. It is available at this link and contains, among others, the following variables:

  • gender, the gender of the student (1 = female, 0 = male);

  • age, the age in years;

  • hsgpa and cogpa, the high school and the college grade point average, on a four-point scale;

  • veg, whether the student is a vegetarian (1 = yes, 0 = no);

  • life, the belief in life after death (1 = yes, 2 = no, 3 = undecided).


  1. Import the data into R and store them in the object students. The read.table function accepts a web address in place of a file name, so there is no need to download the file first.

  2. How many rows and how many columns does students have? Which type does R assign to the variables? Are there missing values?

  3. Note that gender and life are qualitative variables, even though they are stored as numbers. Convert them into factor objects with meaningful labels (see the option labels of factor in the documentation), then obtain the frequency table of life.

  4. Extract the sub-data-frame containing the variables age, hsgpa and cogpa only.

  5. How many students are vegetarian? How many of them are older than 30?

  6. Add to students a new variable gpa_change, the difference between the college and the high school GPA. For how many students did the GPA improve?

References

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