Solution 1
u <- 4
v <- 8
u + v
## [1] 12
u - v
## [1] -4
u * v
## [1] 32
u / v
## [1] 0.5
u^v
## [1] 65536
Solution 2
u <- c(4, 5, 6)
v <- c(1, 2, 3)
u + v
## [1] 5 7 9
u - v
## [1] 3 3 3
u * v
## [1] 4 10 18
u / v
## [1] 4.0 2.5 2.0
u^v
## [1] 4 25 216
Solution 3
u <- c(5, 6, 7, 8)
v <- c(2, 3, 4)
u + v
## Warning in u + v: longer object length is not a multiple of shorter object
## length
## [1] 7 9 11 10
u - v
## Warning in u - v: longer object length is not a multiple of shorter object
## length
## [1] 3 3 3 6
u * v
## Warning in u * v: longer object length is not a multiple of shorter object
## length
## [1] 10 18 28 16
u / v
## Warning in u/v: longer object length is not a multiple of shorter object
## length
## [1] 2.50 2.00 1.75 4.00
u^v
## Warning in u^v: longer object length is not a multiple of shorter object
## length
## [1] 25 216 2401 64
R uses the recycle rule when vectors have different lengths, i.e. it re-uses elements from the shorter vector (starting at the beginning of the vector). In this case, it treats v
as c(2, 3, 4, 2)
(re-using its first element 2
).
Solution 4
Part a
u <- c(8, 9, 10)
v <- c(1, 2, 3)
w <- 0.5 * v
w <- u + w
w <- w^2
w
## [1] 72.25 100.00 132.25
Now check with the original approach:
w <- (u + 0.5 * v) ^ 2
w
## [1] 72.25 100.00 132.25
Part b
w1 <- u + 2
w2 <- u - 5
w <- w1 * w2
w <- w + v
w
## [1] 31 46 63
Now check with the original approach:
w <- (u + 2) * (u - 5) + v
w
## [1] 31 46 63
Part c
w1 <- u + 2
w2 <- u - 5
w2 <- w2 * v
w <- w1 / w2
w
## [1] 3.333333 1.375000 0.800000
Now check with the original approach:
w <- (u + 2) / ((u - 5) * v)
w
## [1] 3.333333 1.375000 0.800000
Solution 5
Part a
w <- ((u + v) / 2) + u
w
## [1] 12.5 14.5 16.5
Now check with the original approach:
w <- u + v
w <- w / 2
w <- w + u
w
## [1] 12.5 14.5 16.5
Part b
w <- (u^3) / (u-v)
w
## [1] 73.14286 104.14286 142.85714
Now check with the original approach:
w1 <- u^3
w2 <- u - v
w <- w1 / w2
w
## [1] 73.14286 104.14286 142.85714
Solution 6
The solution for this exercise is available in our eBook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences.
Solution 7
The solution for this exercise is available in our eBook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences.
Solution 8
The solution for this exercise is available in our eBook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences.
Solution 9
The solution for this exercise is available in our eBook Start Here To Learn R – vol. 1: Vectors, arithmetic, and regular sequences.
Leave a Reply