h <- function(x) {
x^2
}
g <- function(x) {
h(x) + 1
}
f <- function(x) {
g(x) * 2
}
f(10)Exercises A
Programming and Data Analysis with R
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.
What is the value of f(1)? And of f(10^8)?
Approximate f(1) and f(10) to the first two decimal digits.
Draw a plot of the function f(x) over the interval (1,3).
Compute \sum_{k=1}^{K} f(k), for K = 500.
Difficult. The
integratefunction 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?
\sum_{k=0}^n(-1)^k\binom{n}{k} = 0.
\sum_{k=1}^n k \binom{n}{k} = n 2^{n-1}.
\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.
Compute
roots(1, 5, 2);Compute
roots(1, 2, 1);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}.
Write the R function
dist_euclid(x, y)that computes the Euclidean distance between two vectors.If
x = c(1, 4, 2, 2, 10)andy = c(8, 1, 8, 3, 6), what is the value ofdist_euclid(x, y)?Write the R function
frobenius_norm(A)that computes the Frobenius norm of a matrixA.If
A = cbind(1:5,6:10,11:15), what is the value offrobenius_norm(A)?Verify that
dist_euclid(x, y)andfrobenius_norm(x - y)return the same value. Why is that the case?
Let {\bf A} be a matrix of dimension n \times n.
Write a function
diag2(A)that, using aforloop, returns the vector of the diagonal elements a_{11}, \dots, a_{nn} of the matrix {\bf A}.Check that
diag2(A)anddiag(A)return the same vector forA <- matrix(1:25, nrow = 5).
What does the function f(10) return? Discuss the result without running the following code
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.
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?Why does the command
swiss[1:20]return an error? What is the difference with the commandswiss[1:20, ]?Each of the following lines contains an error (a bug). Propose a modification to fix it
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;hsgpaandcogpa, 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).
Import the data into R and store them in the object
students. Theread.tablefunction accepts a web address in place of a file name, so there is no need to download the file first.How many rows and how many columns does
studentshave? Which type does R assign to the variables? Are there missing values?Note that
genderandlifeare qualitative variables, even though they are stored as numbers. Convert them intofactorobjects with meaningful labels (see the optionlabelsoffactorin the documentation), then obtain the frequency table oflife.Extract the sub-data-frame containing the variables
age,hsgpaandcogpaonly.How many students are vegetarian? How many of them are older than 30?
Add to
studentsa new variablegpa_change, the difference between the college and the high school GPA. For how many students did the GPA improve?