Introduction

The purpose of this lab is to get more practice creating and manipulating vectors in the R programming environment. Before you begin this lab you will need to have RStudio (either Cloud or Desktop versions) set up. Open a script file in RStudio and work through the following examples and exercises. Then submit your answers to the exercises using the Lab 1 quiz shell in Canvas. You can submit labs in Canvas as many times as you want up to the due date.

  v = c(4, 9.8, 2, -10, 39, 987)
  u = c(8, 7, 20, 4, 29, 382)
  x = FALSE
  y = TRUE
  a = 2
  b = 1

Exercise 1.

What type of mathematical object (as opposed to R object) is v?

Exercise 2.

What type of R object is v? Hint: use the “class” function.

Exercise 3.

What is the magnitude of v?

Exercise 4.

What is the 3rd element of v-u?

Exercise 5.

What is the 83rd element of rep(x, 100)?

Exercise 6.

What how many elements does c(1:10, v, u, a, b) have?

Exercise 7.

What is the magnitude of c(1:10, v, u, a, b)?

Exercise 8.

What is the 100th element of seq(from = b, to = 50*a, by = 1)?

Random Vectors in R.

There are many ways to build vectors in R, the most basic method is concatenation, which we have been using: c(a, b, …). Another way is to construct them by drawing random numbers, usually from a predetermined distribution. The details of what it means to “draw a random number from a distribution” will be covered in more detail in Week 3, but once the values are drawn we can use them to construct vectors, which we know how to deal with. Type s = rnorm(5,a,b) into the RStudio console. This command is creating a vector s whose components (also called “elements” or “members”) are drawn from a normal distribution with an underlying mean of 2 and a standard deviation of 1 (be sure that a and b are still set at 2 and 1). Don’t worry too much about this- it’s essentially a way of telling R the parameters of how you want these random numbers to be drawn. Also, these aren’t truly random numbers, rather R generates them from a pseudo-random algorithm, but this distinction isn’t important unless you’re working on data that needs to be encrypted.

Execute the command s = rnorm(10000,a,b) twice and verify that the second s vector you generate has different components from the first, but the lengths are the same. (You’re observing that these vectors have randomly generated components.)

Exercise 9.

How many components are in s?

Define the average value of any vector v as the sum of its components divided by the total number of components.

Exercise 10.

Find the average of the s vector.