Section 14 Review Examples


14.1 Example 1


  • Write R code to create a matrix with dimension \(10 \times 2\) with the following conditions.

  • The first column includes values multiple of 3 starting from 3.

  • The second column should include values multiple of 7 starting from 14.

  • Check the attributes of the created matrix

  • Give the rownames as first 10 lower case letters and colnames as ‘m3’ and ‘m7’


14.2 Example 2


  • Write R code to create the array shown below.

  • Note, the array [,,1] contain first 12 positive odd numbers and the array [,,2] contain first 12 positive even numbers.

  • Check the attributes of the array.

, , 1

     [,1] [,2] [,3]
[1,]    1    9   17
[2,]    3   11   19
[3,]    5   13   21
[4,]    7   15   23

, , 2

     [,1] [,2] [,3]
[1,]    2   10   18
[2,]    4   12   20
[3,]    6   14   22
[4,]    8   16   24


14.3 Example 3


  • Set the seed as 12345.

  • Generate a random sample of size 20 from a normal distribution with mean=10, sd=2. Name this vector as Wt. Round the values to two decimal places.

  • Generate random uniform sample of size 20 between 1 to 2. Name this vector as Age. Round the values to two decimal places.

  • Create a character vector of size 20 with first 5 elements as M and the second 5 elements as F. Name this vector as Sex.

  • Create a logical vector of size 20 using random sampling. Name this vector as Vac.

  • Now create a data.frame that includes four columns: Wt, Age, Sex and Vac.

  • Explore the created data.frame.

  • Conduct a t.test to check if there is a difference in Wt between male and female babies.


14.4 Example 4


  • Load the iris data that you saved earlier.

  • Calculate number of observations for each species.

  • Calculate the following estimates for Sepal.Length, Sepal.Width, Petal.Length, Petal.Width

    • Mean
    • Median
    • Standard deviation
    • Coefficient of variation (SD/Mean)
  • Create a list with the following information

    • Size of the data
    • Levels of Species
    • Mean, Median, SD and CV


14.5 Example 5


  • Load the iris data that you saved earlier.

  • Use the following formula of Arithmetic Mean (AM), Geometric Mean (GM) and Harmonic Mean (HM) to calculate AM, GM and HM of Sepal.Length and Petal.Length.

\[ \large AM = (x_1 + x_2 + ... + x_n)/n = \frac{1}{n}\sum\limits_{i=1}^{n} x_{i}\]

\[ \large GM = \sqrt[n]{(x_1 x_2 ... x_n)} = \left( \prod \limits_{i=1}^{n} x_{i} \right) ^{\frac{1}{n}} \]

\[ \large HM = \frac{n}{(\frac{1}{x_1} + \frac{1}{x_2} + ... + \frac{1}{x_n})} = \frac{n}{\sum\limits_{i=1}^{n} \frac{1}{x_i}}\]