gas_bill <- c(46, 33, 39, 37, 46, 30, 48, 32, 49, 35, 30, 48)
length(gas_bill)
## [1] 12
sum(gas_bill > 40)
## [1] 5
The expression gas_bill > 40
is a logical vector.
Summing this vector gives the number of TRUE elements.
mean(gas_bill > 40) * 100
## [1] 41.66667
The mean of a logical vector is the proportion of TRUE elements.
sum(gas_bill[gas_bill > 40])
## [1] 237
gas_bill_update <- gas_bill + c(-3, 7)
The shorter vector c(-3, 7)
is recycled to match the
length of gas_bill
.
sum(gas_bill - gas_bill_update)
## [1] -24
So I owe the company 24 dollars.
sum(sqrt(1:100))
## [1] 671.4629
prod(log(100:200))
## [1] 3.034637e+70
ints <- 1:100
ints_sq <- ints^2
sum(ints[ints_sq > 300 & ints_sq < 500])
## [1] 100
Pay special attention to the expression
ints_sq > 300 & ints_sq < 500
above.
(mx <- matrix(1:17, nrow = 4, ncol = 5))
## Warning in matrix(1:17, nrow = 4, ncol = 5): data length [17] is not a sub-
## multiple or multiple of the number of rows [4]
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 5 9 13 17
## [2,] 2 6 10 14 1
## [3,] 3 7 11 15 2
## [4,] 4 8 12 16 3
The first three entries of 1:17
were recycled. The
warning tells us the recycling was not complete.
mx[c(1, 4), c(1, 2, 5)]
## [,1] [,2] [,3]
## [1,] 1 5 17
## [2,] 4 8 3
mx[mx > 10] <- 0
mx
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 5 9 0 0
## [2,] 2 6 10 0 1
## [3,] 3 7 0 0 2
## [4,] 4 8 0 0 3
First, mx[mx > 10]
filters for the entries larger
than 10. Then, 0
is recycled to match the length of these
entries. Finally, the entries are each assigned to 0.