Exercises Chapter 3

Exercise 4.

Read data:

x = c(1.3, 7, 3.6, 4.1, 5)

Calculate mean:

mean(x)
## [1] 4.2

Store mean of x in mx:

mx = mean(x)

Calculate deviations from mean (2 possible ways):

devx1 = x - mean(x)  # Using the mean directly
devx2 = x - mx  # Using the mean stored in mx
# Lets look at them, side-by-side
cbind(devx1, devx2)
##      devx1 devx2
## [1,]  -2.9  -2.9
## [2,]   2.8   2.8
## [3,]  -0.6  -0.6
## [4,]  -0.1  -0.1
## [5,]   0.8   0.8

The sum should be zero

sum(devx1)
## [1] -1.332e-15
sum(devx2)
## [1] -1.332e-15

In practice, -1.3323 × 10-15 is equal to zero, due to rounding it is a pretty small number. We can use round() to round off:

round(sum(devx1), 3)
## [1] 0

Exercise 18.

rm(list = ls())  # remove and clean up ALL objects

Read data:

x = c(41, 15, 39, 54, 31, 15, 33)

Find mean, median and mode:

mean(x)
## [1] 32.57
median(x)
## [1] 33

To get the mode we need the package “modeest”

library(modeest)
## This is package 'modeest' written by P. PONCET. For a complete list of
## functions, use 'library(help = "modeest")' or 'help.start()'.
mlv(x, method = "mfv")
## Mode (most likely value): 15 
## Bickel's modal skewness: 0.7143 
## Call: mlv.default(x = x, method = "mfv")

Exercise 28.

rm(list = ls())  # remove and clean up ALL objects

Read data:

x = c(2, 8, 6, 4, 10, 6, 8, 4)

We use a version of the GM formula derived from: http://en.wikipedia.org/wiki/Geometric_mean

exp(mean(log(x)))
## [1] 5.413

Mean Deviation (p.77).

Read data:

Orange = c(20, 40, 50, 60, 80)
mean(Orange)
## [1] 50
median(Orange)
## [1] 50
range(Orange)
## [1] 20 80
deviation = Orange - mean(Orange)
deviation
## [1] -30 -10   0  10  30
absolute.deviation = abs(deviation)
absolute.deviation
## [1] 30 10  0 10 30
MD = sum(absolute.deviation)/length(Orange)
MD
## [1] 16

Variance (p.83).

rm(list = ls())  # remove and clean up ALL objects

Read data:

x = c(12, 20, 16, 18, 19)
cbind(mean(x), x - mean(x), (x - mean(x))^2)  # Table from example solution
##      [,1] [,2] [,3]
## [1,]   17   -5   25
## [2,]   17    3    9
## [3,]   17   -1    1
## [4,]   17    1    1
## [5,]   17    2    4
s2 = sum((x - mean(x))^2)/(length(x) - 1)
s2
## [1] 10
s = sqrt(s2)
s
## [1] 3.162
# Use built in R functions
var(x)
## [1] 10
sd(x)
## [1] 3.162