x <- c(6, 30, 19, -4, 3, 5, -2, -14)Exercise 1 - solved
Vectors
1 - Basics
Let:
- What is the number of elements in
x?
length(x)- What is the smallest element of
x?
min(x)- What is the largest element of
x?
max(x)- Calculate the sum of \(x^2\).
sum(x^2)- Extract the third element of
x.
x[3]- Extract the odd-indexed elements of
x(1,3,5-th,… places).
x[seq(1,length(x),2)]- Calculate the square root of the product of
x.
# Impossible, because prod(x) < 0
sqrt(prod(x))- Sort the vector
xin ascending order.
sort(x)- Sort the vector
xin descending order.
sort(x,decreasing = TRUE)
rev(sort(x))- Extract a sub-vector of the negative elements of
x.
x[x<0]- What is the proportion of positive elements in
x?
mean(x>0)- Locate the indexes of the extrema (minimun and maximum) of
x.
which.min(x)
which.max(x)2 - Creating vectors
- Create the following vector:
1 2 3 4 5 6 7 6 5 4 3 2 1.
c(1:6,7:1)- Create the sequence
1, 3, 5, ..., 39and store it inx.
x <- seq(1,39,2)- Create an evenly-spaced sequence from 1 to 99 with 9 elements.
seq(1,99,length.out = 9)- Let
hw <- 95andexam <- 90be the homework and final exam grades of a student. Write a command that computes the student’s final grade given that the homework constitutes 15%.
hw <- 95
exam <- 90
0.15 * hw + 0.85 * exam- Following the previous item, let
hw <- c(95,100, 90, 85, 0, 90, 90)andexam <- c(90,100, 80, 81, 75, 60, 80). Assign the vectorgradeswith the final grades corresponding to these achievements. The passing grade is 65. Round the grades to the nearest integer usinground. Print both the rounded and un-rounded grades. Do you notice anything surprising?1
hw <- c(95,100, 90, 85, 0, 90, 90)
exam <- c(90,100, 80, 81, 75, 60, 80)
grades <- 0.15 * hw + 0.85 * exam
grades
round(grades)3 - Recycling rule
- Create the vector:
1 -2 3 -4 5 -6 7 -8 9 -10 11 -12and assign it toy.
y <- 1:12 * c(1,-1)- Add 1 only to even-indexed elements of
y(that is to -2,-4,-6,…).
y + c(0,1)- Analyze what happens when you run the following command.
1:10 + 1:4Footnotes
The rounding rule employed in R for .5 is IEC 60599, which says ‘go to the nearest even digit’. See
?roundfor details.↩︎