In this lab you can use the interactive console to explore or Knit the document. Remember anything you type here can be “sent” to the console with Cmd-Enter (OS-X) or Cntr-Enter (Windows/Linux) in an R code chunk.

Part 1

  1. Create a new variable called my.num that contains 6 numbers.
my.num <- c(5,4,7,8,12,14) # These can be any real numbers
  1. Multiply my.num by 4.
my.num * 4 
## [1] 20 16 28 32 48 56
  1. Create a second variable called my.char that contains 5 character strings.
my.char <- c("banana", "garlic", "pickles", "hot chocolate", "7-Up") # Again,these can be anything
  1. Combine the two variables my.num and my.char into a variable called both.
both <- c(my.num, my.char)
  1. What is the length of both?
length(both)
## [1] 11
  1. What class is both?
class(both)
## [1] "character"

Part 2

  1. Divide both by 3, what happens?
both / 3
## Error in both/3: non-numeric argument to binary operator
  1. Create a vector with elements 1 2 3 4 5 6 and call it x.
x <- c(1, 2, 3, 4, 5, 6)
  1. Create another vector with elements 10 20 30 40 50 60 and call it y.
y <- c(10, 20, 30, 40, 50, 60)
  1. The code z <- y[1:5] saves the first five items in y as the new variable z. Print z.
z <- y[1:5]
print(z)
## [1] 10 20 30 40 50
  1. What happens when you add x and z together? How is this different from #10 ?
x + z
## Warning in x + z: longer object length is not a multiple of shorter object
## length
## [1] 11 22 33 44 55 16
# R "auto replicates" the shorter vector when the vectors aren't the same length - this is not what we want!
# In this case, it reads y as c(10, 20, 30, 40, 50, 10)!
  1. Append the value 100 onto the vector z (hint: you can use the c() function).
z <- c(z, 100)
  1. Add x and z together.
x + z
## [1]  11  22  33  44  55 106
  1. Multiply x and z together. How is this similar to the way R performs addition in #13 ?
x * z
## [1]  10  40  90 160 250 600
# R adds together the first element of each vector, then the second, and so on. This order also applies when multiplying!